-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path01_binary_tree_traversal_preorder.py
55 lines (40 loc) · 1.27 KB
/
01_binary_tree_traversal_preorder.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
47
48
49
50
51
52
53
54
55
class Node(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BinaryTree(object):
def __init__(self, root):
self.root = Node(root)
def print_tree(self, traversal_type):
if traversal_type == "preorder":
return self.preorder_print(self.root, "")
else:
print("Traversal type " + str(traversal_type) + " is not supported.")
return False
def preorder_print(self, start, traversal):
# Root -> Left -> Right
if start:
traversal += (str(start.value) + "-")
traversal = self.preorder_print(start.left, traversal)
traversal = self.preorder_print(start.right, traversal)
return traversal
'''
Pre-Order Traversal
1
/ \
2 3
/ \ / \
4 5 6 7
1-2-4-5-3-6-7-
'''
if __name__ == "__main__":
tree = BinaryTree(1)
tree.root.left = Node(2)
tree.root.right = Node(3)
tree.root.left.left = Node(4)
tree.root.left.right = Node(5)
tree.root.right.left = Node(6)
tree.root.right.right = Node(7)
X = tree.print_tree("preorder")
print(X)