-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.py
68 lines (53 loc) · 1.45 KB
/
main.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
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
'''
The binary tree in this example is shown as follow
1
/ \
2 3
/ \ /
4 5 6
/
7
post-order traversal: 4 7 5 2 6 3 1
'''
def postorder_traversal_by_recursion(root):
if not root:
return
postorder_traversal_by_recursion(root.left)
postorder_traversal_by_recursion(root.right)
print(root.val, end=" ")
def postorder_traversal(root):
if not root:
return
nodeStack, pre = [], None
nodeStack.append(root)
while len(nodeStack):
cur = nodeStack[len(nodeStack) - 1]
if cur.left and cur.left != pre and cur.right != pre:
nodeStack.append(cur.left)
elif cur.right and cur.right != pre:
nodeStack.append(cur.right)
else:
print(cur.val, end=" ")
pre = cur
nodeStack.pop()
def generate_B_tree(nodes, index):
node = None
if index < len(nodes) and nodes[index]:
node = TreeNode(nodes[index])
node.left = generate_B_tree(nodes, index * 2 + 1)
node.right = generate_B_tree(nodes, index * 2 + 2)
return node
def main():
nodes = [1, 2, 3, 4, 5, 6, None, None, None, 7]
root = generate_B_tree(nodes, 0)
postorder_traversal_by_recursion(root)
print()
postorder_traversal(root)
print()
if __name__ == '__main__':
main()