-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinaryTreePostorderTraversal.py
43 lines (41 loc) · 1.04 KB
/
BinaryTreePostorderTraversal.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
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def postorderTraversal(self, root: TreeNode) -> List[int]:
'''
ac
recursive - trivial
iterative - do a normal iterative dfs(preorder)
then reverse the output
complexity: O(n) (each node visited once)
'''
'''
#recursive
def trav(root):
if not root:
return
trav(root.left)
trav(root.right)
r.append(root.val)
return
r = []
trav(root)
return r
'''
#iterative
stack = [root]
r = []
if not root:
return []
while stack:
curr = stack.pop(-1)
if curr.left:
stack.append(curr.left)
if curr.right:
stack.append(curr.right)
r.append(curr.val)
return r[::-1]