Skip to content

Commit f1c86af

Browse files
authored
Add doctests and then streamline display() and is_full_binary_tree()
1 parent 039cdb3 commit f1c86af

File tree

1 file changed

+52
-25
lines changed

1 file changed

+52
-25
lines changed

data_structures/binary_tree/basic_binary_tree.py

+52-25
Original file line numberDiff line numberDiff line change
@@ -3,53 +3,80 @@
33

44
class Node:
55
"""
6-
This is the Class Node with a constructor that contains data variable to type data
7-
and left, right pointers.
6+
A Node has data variable and pointers to Nodes to its left and right.
87
"""
9-
108
def __init__(self, data: int) -> None:
119
self.data = data
1210
self.left: Optional[Node] = None
1311
self.right: Optional[Node] = None
1412

1513

16-
def display(tree: Node) -> None: # In Order traversal of the tree
17-
18-
if tree is None:
19-
return
20-
21-
if tree.left is not None:
14+
def display(tree: Optional[Node]) -> None: # In Order traversal of the tree
15+
"""
16+
>>> root = Node(1)
17+
>>> root.left = Node(0)
18+
>>> root.right = Node(2)
19+
>>> display(root)
20+
0
21+
1
22+
2
23+
>>> display(root.right)
24+
2
25+
"""
26+
if tree:
2227
display(tree.left)
23-
24-
print(tree.data)
25-
26-
if tree.right is not None:
28+
print(tree.data)
2729
display(tree.right)
2830

29-
return
30-
3131

32-
def depth_of_tree(tree: Node,) -> int:
32+
def depth_of_tree(tree: Optional[Node]) -> int:
3333
"""
34-
Recursive function that finds the depth of a binary tree.
34+
Recursive function that returns the depth of a binary tree.
35+
36+
>>> root = Node(0)
37+
>>> depth_of_tree(root)
38+
1
39+
>>> root.left = Node(0)
40+
>>> depth_of_tree(root)
41+
2
42+
>>> root.right = Node(0)
43+
>>> depth_of_tree(root)
44+
2
45+
>>> root.left.right = Node(0)
46+
>>> depth_of_tree(root)
47+
3
48+
>>> depth_of_tree(root.left)
49+
2
3550
"""
36-
3751
return 1 + max(depth_of_tree(tree.left), depth_of_tree(tree.right)) if tree else 0
3852

3953

40-
def is_full_binary_tree(tree: Node,) -> bool:
54+
def is_full_binary_tree(tree: Node) -> bool:
4155
"""
4256
Returns True if this is a full binary tree
43-
"""
4457
45-
if tree is None:
46-
return True
47-
if (tree.left is None) and (tree.right is None):
58+
>>> root = Node(0)
59+
>>> is_full_binary_tree(root)
60+
True
61+
>>> root.left = Node(0)
62+
>>> is_full_binary_tree(root)
63+
False
64+
>>> root.right = Node(0)
65+
>>> is_full_binary_tree(root)
66+
True
67+
>>> root.left.left = Node(0)
68+
>>> is_full_binary_tree(root)
69+
False
70+
>>> root.right.right = Node(0)
71+
>>> is_full_binary_tree(root)
72+
False
73+
"""
74+
if not tree:
4875
return True
49-
if (tree.left is not None) and (tree.right is not None):
76+
if tree.left and tree.right:
5077
return is_full_binary_tree(tree.left) and is_full_binary_tree(tree.right)
5178
else:
52-
return False
79+
return not tree.left and not tree.right
5380

5481

5582
def main() -> None: # Main function for testing.

0 commit comments

Comments
 (0)