-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinaryTreeClass.py
63 lines (45 loc) · 1.65 KB
/
binaryTreeClass.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
56
57
58
59
60
61
62
63
# https://www.youtube.com/watch?v=6oL-0TdVy28
# Common depth first search order: inorder, preorder, postorder
class Node():
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BinaryTree():
def __init__(self, root):
self.root = Node(root)
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
def inorder_print(self, start, traversal):
"""Left->Root->Right"""
if start:
traversal = self.inorder_print(start.left, traversal)
traversal += str(start.value) + "-"
traversal = self.inorder_print(start.right, traversal)
return traversal
def postorder_print(self, start, traversal):
if start:
traversal = self.postorder_print(start.left, traversal)
traversal = self.postorder_print(start.right, traversal)
traversal += str(start.value) + "-"
return traversal
'''
1
2 3
4 5 6 7
'''
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)
print(tree.preorder_print(tree.root,"")) # 1, 2, 4, 5, 3, 6, 7
print(tree.inorder_print(tree.root,"")) # 4 2 5 1 6 3 7
print(tree.postorder_print(tree.root,"")) # 4 5 2 6 7 3 1