-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
094_Binary_Tree_Inorder_Traversal.py
79 lines (73 loc) · 2.31 KB
/
094_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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# 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]
# """
# # recursively
# res = []
# self.do_inorderTraversal(res, root)
# return res
#
# def do_inorderTraversal(self, res, curr):
# if curr is None:
# return
# if curr.left is not None:
# self.do_inorderTraversal(res, curr.left)
# res.append(curr.val)
# if curr.right is not None:
# self.do_inorderTraversal(res, curr.right)
# def inorderTraversal(self, root):
# # iteratively, but break the tree
# res = []
# if root is None:
# return res
# queue = [root]
# while len(queue) > 0:
# curr = queue.pop(0)
# if curr.left is None and curr.right is None:
# res.append(curr.val)
# else:
# if curr.right is not None:
# queue.insert(0, curr.right)
# curr.right = None
# queue.insert(0, curr)
# if curr.left is not None:
# queue.insert(0, curr.left)
# curr.left = None
# return res
# def inorderTraversal(self, root):
# res = []
# stack = []
# while root is not None:
# stack.append(root)
# root = root.left
# while root is None:
# if len(stack) == 0:
# return res
# root = stack.pop()
# res.append(root.val)
# root = root.right
# return res
def inorderTraversal(self, root):
if root is None:
return []
res = []
stack = [root]
while len(stack) > 0:
curr = stack.pop()
if not isinstance(curr, TreeNode):
res.append(curr)
continue
if curr.right is not None:
stack.append(curr.right)
stack.append(curr.val)
if curr.left is not None:
stack.append(curr.left)
return res