Skip to content

Commit 88a18dc

Browse files
committed
Binary tree in-order traversal solution
1 parent f822b58 commit 88a18dc

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed

94_binary_tree_inorder_traversal.py

+79
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
# Definition for a binary tree node.
2+
# class TreeNode(object):
3+
# def __init__(self, x):
4+
# self.val = x
5+
# self.left = None
6+
# self.right = None
7+
8+
class Solution(object):
9+
# def inorderTraversal(self, root):
10+
# """
11+
# :type root: TreeNode
12+
# :rtype: List[int]
13+
# """
14+
# # recursively
15+
# res = []
16+
# self.do_inorderTraversal(res, root)
17+
# return res
18+
#
19+
# def do_inorderTraversal(self, res, curr):
20+
# if curr is None:
21+
# return
22+
# if curr.left is not None:
23+
# self.do_inorderTraversal(res, curr.left)
24+
# res.append(curr.val)
25+
# if curr.right is not None:
26+
# self.do_inorderTraversal(res, curr.right)
27+
28+
# def inorderTraversal(self, root):
29+
# # iteratively, but break the tree
30+
# res = []
31+
# if root is None:
32+
# return res
33+
# queue = [root]
34+
# while len(queue) > 0:
35+
# curr = queue.pop(0)
36+
# if curr.left is None and curr.right is None:
37+
# res.append(curr.val)
38+
# else:
39+
# if curr.right is not None:
40+
# queue.insert(0, curr.right)
41+
# curr.right = None
42+
# queue.insert(0, curr)
43+
# if curr.left is not None:
44+
# queue.insert(0, curr.left)
45+
# curr.left = None
46+
# return res
47+
# def inorderTraversal(self, root):
48+
# res = []
49+
# stack = []
50+
# while root is not None:
51+
# stack.append(root)
52+
# root = root.left
53+
# while root is None:
54+
# if len(stack) == 0:
55+
# return res
56+
# root = stack.pop()
57+
# res.append(root.val)
58+
# root = root.right
59+
# return res
60+
61+
def inorderTraversal(self, root):
62+
if root is None:
63+
return []
64+
res = []
65+
stack = [root]
66+
while len(stack) > 0:
67+
curr = stack.pop()
68+
if not isinstance(curr, TreeNode):
69+
res.append(curr)
70+
continue
71+
if curr.right is not None:
72+
stack.append(curr.right)
73+
stack.append(curr.val)
74+
if curr.left is not None:
75+
stack.append(curr.left)
76+
return res
77+
78+
79+

0 commit comments

Comments
 (0)