-
Notifications
You must be signed in to change notification settings - Fork 8
/
binary_inorder.py
50 lines (45 loc) · 1.06 KB
/
binary_inorder.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
'''
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree {0,#,1,2},
0
\
1
/
2
return [0,2,1].
'''
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
result = []
stack = []
p = root
while p or stack:
# Save the nodes which have left child
while p:
stack.append(p)
p = p.left
if stack:
p = stack.pop()
# Visit the middle node
result.append(p.val)
# Visit the right subtree
p = p.right
return result
if __name__ == "__main__":
n1 = TreeNode(0)
n2 = TreeNode(1)
n3 = TreeNode(2)
n1.right = n2
n2.left = n3
assert Solution().inorderTraversal(n1) == [0, 2, 1]