Skip to content

Commit b40463b

Browse files
committed
Allow Node from list
1 parent 24602ef commit b40463b

1 file changed

Lines changed: 50 additions & 4 deletions

File tree

vicutils/printBin.py

Lines changed: 50 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,23 +10,69 @@ class BinaryNode:
1010
"""
1111
Represents a node in a binary tree.
1212
13+
Args:
14+
val: The value stored in the node, or a list to build a tree from.
15+
If a list is provided, builds tree level by level from left to right.
16+
Use None in the list for missing nodes.
17+
left: Reference to the left child node (only used when val is not a list)
18+
right: Reference to the right child node (only used when val is not a list)
19+
1320
Attributes:
1421
val: The value stored in the node
1522
left: Reference to the left child node
1623
right: Reference to the right child node
24+
25+
Example:
26+
>>> # Create a single node
27+
>>> node = BinaryNode(5)
28+
>>>
29+
>>> # Create a tree from a list
30+
>>> root = BinaryNode([1, 2, 3, 4, 5, None, 7])
31+
>>> # Creates:
32+
>>> # 1
33+
>>> # / \
34+
>>> # 2 3
35+
>>> # / \ \
36+
>>> # 4 5 7
1737
"""
1838
def __init__(self, val=0, left=None, right=None):
19-
self.val = val
20-
self.left = left
21-
self.right = right
39+
# If val is a list, build tree from it
40+
if isinstance(val, list):
41+
if not val or val[0] is None:
42+
raise ValueError("Cannot create tree from empty list or list starting with None")
43+
44+
self.val = val[0]
45+
self.left = None
46+
self.right = None
47+
48+
queue = [self]
49+
i = 1
50+
51+
while queue and i < len(val):
52+
node = queue.pop(0)
53+
54+
# Add left child
55+
if i < len(val) and val[i] is not None:
56+
node.left = BinaryNode(val[i])
57+
queue.append(node.left)
58+
i += 1
59+
60+
# Add right child
61+
if i < len(val) and val[i] is not None:
62+
node.right = BinaryNode(val[i])
63+
queue.append(node.right)
64+
i += 1
65+
else:
66+
self.val = val
67+
self.left = left
68+
self.right = right
2269

2370
def __str__(self):
2471
return str(self.val)
2572

2673
def __repr__(self):
2774
return str(self)
2875

29-
3076
def center(val, unitSize=None, fillChar=None):
3177
"""
3278
Centers a value within a fixed width string.

0 commit comments

Comments
 (0)