-
Notifications
You must be signed in to change notification settings - Fork 19
/
27_Inorder-Traversal.py
40 lines (32 loc) · 918 Bytes
/
27_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
#!/usr/bin/python
# coding=utf-8
'''
__author__ = 'sunp'
__date__ = '2019/1/26'
Given a binary search tree, print out the elements of the tree in order without using recursion.
'''
class TreeNode(object):
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def inorder_traversal(root):
res, stack = [], []
while root or stack:
if root:
stack.append(root)
root = root.left
else:
tmp = stack.pop()
res.append(tmp.val)
root = tmp.right
return res
if __name__ == '__main__':
test = TreeNode(5)
test.left = TreeNode(2)
test.left.left = TreeNode(1)
test.left.right = TreeNode(3)
test.right = TreeNode(7)
test.right.left = TreeNode(6)
test.right.right = TreeNode(8)
assert inorder_traversal(test) == [1, 2, 3, 5, 6, 7, 8]