-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinary Tree Postorder Traversal
38 lines (36 loc) · 1.07 KB
/
Binary Tree Postorder 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
# 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 postorderTraversal(self, root):
result=[]
if root:
result.append(root.val)
# right first
if root.right:
result=self.postorderTraversal(root.right)+result
if root.left:
result=self.postorderTraversal(root.left)+result
return result
'''
# iterative
def postorderTraversal(self,root):
if not root:
return []
waitlist,result=[(root,False)],[]
while waitlist:
p,visited=waitlist.pop()
if p:
if not visited:
waitlist.append((p,True))
waitlist.append((p.right,False))
waitlist.append((p.left,False))
else:
result.append(p.val)
return result