-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathiterativeBinaryTreeInorderTraversal.py
More file actions
42 lines (38 loc) · 1.19 KB
/
iterativeBinaryTreeInorderTraversal.py
File metadata and controls
42 lines (38 loc) · 1.19 KB
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
# Given a binary tree, return the inorder traversal of its nodes' values.
# Recursive solution is trivial, could you do it iteratively ?
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: A Tree
@return: Inorder in ArrayList which contains node values.
"""
def inorderTraversal(self, root):
# write your code here
stack = []
res = []
root = self.handleLeftTree(root, stack, res)
while root:
if root.right:
root = root.right
root = self.handleLeftTree(root, stack, res)
else:
if len(stack) > 0: # python can not pop an empty list
root = stack.pop(-1)
res.append(root.val)
else:
root = None # the key to escape the while loop
return res
def handleLeftTree(self, root, stack, res):
if root is None:
return
while root.left:
stack.append(root)
root = root.left
res.append(root.val)
return root