-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtree_traversal.py
46 lines (32 loc) · 1.17 KB
/
tree_traversal.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
from BinarySearchTree import BinarySearchTree, TreeNode
b = BinarySearchTree()
for i in [8, 4, 2, 6, 10, 20]:
b.put(i, i)
def in_order_print(node: TreeNode) -> None:
"""Traverses a binary tree in order.
Visits the nodes in ascending order. Fully explores left branch, then the
current node and finally the right branch.
"""
if node is not None:
in_order_print(node.left_child)
print(node.value)
in_order_print(node.right_child)
def pre_order_print(node: TreeNode) -> None:
"""Traverses a binary tree in pre-order.
Visits the current node first before fully exploring the left branch, then
the right branch.
"""
if node is not None:
print(node.value)
pre_order_print(node.left_child)
pre_order_print(node.right_child)
def post_order_print(node: TreeNode) -> None:
"""Traverses a binary tree in post-order.
Visits all child nodes before the current node. Fully exploring the left
branch, then the right branch.
"""
if node is not None:
post_order_print(node.left_child)
post_order_print(node.right_child)
print(node.value)
post_order_print(b.root)