-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary_tree.py
89 lines (74 loc) · 2.55 KB
/
binary_tree.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
class TreeNode(object):
def __init__(self, value, left=None, right=None):
self.val = value
self.left = left
self.right = right
class BinaryTree(object):
def __init__(self):
self.root = None
def isNodeFull(self, node):
if node.left and node.right:
return True
return False
def insert(self, val):
node = TreeNode(val)
if self.root is None:
self.root = node
else:
temp = self.root
while True:
if temp.left is None:
temp.left = node
break
elif temp.right is None:
temp.right = node
break
if self.isNodeFull(temp.left) and not self.isNodeFull(temp.right):
temp = temp.right
else:
temp = temp.left
def insertNode(self, node):
self.root = node
def show(self, method="inorder"):
if method == "inorder":
traversal = self._inOrderTraversal
elif method == "preorder":
traversal = self._preOrderTraversal
elif method == "postorder":
traversal = self._postOrderTraversal
result = []
result = traversal(self.root, result)
print("{} traversal:".format(method))
print([node.val for node in result])
def _preOrderTraversal(self, rootNode, result=[]):
if rootNode:
result.append(rootNode)
self._preOrderTraversal(rootNode.left, result)
self._preOrderTraversal(rootNode.right, result)
return result
def _postOrderTraversal(self, rootNode, result=[]):
if rootNode:
self._postOrderTraversal(rootNode.left, result)
self._postOrderTraversal(rootNode.right, result)
result.append(rootNode)
return result
def _inOrderTraversal(self, rootNode, result=[]):
if rootNode:
self._inOrderTraversal(rootNode.left, result)
result.append(rootNode)
self._inOrderTraversal(rootNode.right, result)
return result
if __name__ == "__main__":
tree = BinaryTree()
for idx in range(1, 11):
tree.insert(idx)
tree.show()
# D = TreeNode("D", TreeNode("C"), TreeNode("E"))
# B = TreeNode("B", TreeNode("A"), D)
# I = TreeNode("I", TreeNode("H"))
# G = TreeNode("G", None, I)
# F = TreeNode("F", B, G)
# tree.insertNode(F)
# tree.show("inorder")
# tree.show("preorder")
# tree.show("postorder")