-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy path145_Binary_Tree_Postorder_Traversal.py
57 lines (54 loc) · 1.61 KB
/
145_Binary_Tree_Postorder_Traversal.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
# def postorderTraversal(self, root):
# """
# :type root: TreeNode
# :rtype: List[int]
# """
# # Recursion
# if root is None:
# return []
# res = []
# self.postorderHelp(root, res)
# return res
#
# def postorderHelp(self, node, stack):
# if node is None:
# return
# self.postorderHelp(node.left, stack)
# self.postorderHelp(node.right, stack)
# stack.append(node.val)
# def postorderTraversal(self, root):
# # Stack
# if root is None:
# return []
# res = []
# stack = [root]
# while len(stack) > 0:
# curr = stack.pop()
# res.insert(0, curr.val)
# if curr.left is not None:
# stack.append(curr.left)
# if curr.right is not None:
# stack.append(curr.right)
# return res
def postorderTraversal(self, root):
if root is None:
return []
res = []; stack = [root]
while len(stack) > 0:
curr = stack.pop()
if not isinstance(curr, TreeNode):
res.append(curr)
continue
stack.append(curr.val)
if curr.right is not None:
stack.append(curr.right)
if curr.left is not None:
stack.append(curr.left)
return res