-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinary Tree Inorder Traversal
53 lines (51 loc) · 1.51 KB
/
Binary Tree Inorder Traversal
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
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param {TreeNode} root
# @return {integer[]}
'''
# recursive
def inorderTraversal(self, root):
if root:
result=[root.val]
if root.left:
result=self.inorderTraversal(root.left)+result
if root.right:
result=result+self.inorderTraversal(root.right)
else:
result=[]
return result # returned result will be added
'''
# iterative 1
def inorderTraversal(self,root):
waitlist,p,result=[],root,[]
while waitlist or p:
while p:
# order in waitlist decide the "inorder"
waitlist.append(p)
# find left edge node first
p=p.left
p=waitlist.pop()
result.append(p.val)
#then right
p=p.right
return result
# iterative 2
def inorderTraversal(self,root):
if not root:
return []
waitlist,result=[(root,False)],[]
while waitlist:
p,visited=waitlist.pop()
if p:
if visited:
result.append(p.val)
else:
waitlist.append((p.right,False))
waitlist.append((p,True))
waitlist.append((p.left,False))
return result