forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
postorder.py
41 lines (35 loc) · 815 Bytes
/
postorder.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
'''
Time complexity : O(n)
'''
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def postorder(root):
res_temp = []
res = []
if not root:
return res
stack = []
stack.append(root)
while stack:
root = stack.pop()
res_temp.append(root.val)
if root.left:
stack.append(root.left)
if root.right:
stack.append(root.right)
while res_temp:
res.append(res_temp.pop())
return res
# Recursive Implementation
def postorder_rec(root, res=None):
if root is None:
return []
if res is None:
res = []
postorder_rec(root.left, res)
postorder_rec(root.right, res)
res.append(root.val)
return res