-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtree_traversal.py
60 lines (44 loc) · 1.33 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def preOrderTraversal(rootNode, result=[]):
if rootNode:
result.append(rootNode)
preOrderTraversal(rootNode.left)
preOrderTraversal(rootNode.right)
return result
def inOrderTraversal(rootNode, result=[]):
if rootNode:
inOrderTraversal(rootNode.left)
result.append(rootNode)
inOrderTraversal(rootNode.right)
return result
def postOrderTraversal(rootNode, result=[]):
if rootNode:
postOrderTraversal(rootNode.left)
postOrderTraversal(rootNode.right)
result.append(rootNode)
return result
def printTree(order):
for node in order:
print("{}->".format(node.val), end="")
print()
if __name__ == "__main__":
root = TreeNode(1)
root.left = TreeNode(2)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
root.right = TreeNode(3)
root.right.left = TreeNode(6)
root.right.right = TreeNode(7)
preOrder = preOrderTraversal(root)
print("Pre-order traversal:")
printTree(preOrder)
inOrder = inOrderTraversal(root)
print("In-order traversal:")
printTree(inOrder)
postOrder = postOrderTraversal(root)
print("Post-order traversal:")
printTree(postOrder)