-
Notifications
You must be signed in to change notification settings - Fork 1
/
binary-tree-inorder-traversal.py
58 lines (46 loc) · 1.41 KB
/
binary-tree-inorder-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
#!/usr/bin/python3
# https://leetcode.com/problems/binary-tree-inorder-traversal/
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def create_binary_tree(array):
root = TreeNode(array[0])
queue = [(0, root)]
while len(queue) > 0:
(i, p) = queue.pop(0)
li = i + 1
ri = i + 2
if li < len(array) and array[li] is not None:
t = TreeNode(array[li])
p.left = t
queue.append((li, t))
if ri < len(array) and array[ri] is not None:
t = TreeNode(array[ri])
p.right = t
queue.append((ri, t))
return root
def inorder_traversal_recursive(root):
if root:
inorder_traversal_recursive(root.left)
print(root.val)
inorder_traversal_recursive(root.right)
def inorder_traversal_iterative(root):
stack = []
output = []
while len(stack) > 0 or root:
if root:
stack.append(root)
root = root.left
else:
root = stack.pop()
print(root.val)
output.append(root.val)
root = root.right
return output
if __name__ == "__main__":
tree_array = [1, None, 2, 3]
root_node = create_binary_tree(tree_array)
# inorder_traversal_recursive(root_node)
print(inorder_traversal_iterative(root_node))