-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinaryTreePostorderTraversal.py
81 lines (73 loc) · 2.08 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return a list of integers
def postorderTraversal(self, root):
list = []
stack = []
pre = None
if root:
stack.append(root)
while stack:
curr = stack[len(stack)-1]
if (curr.left == None and curr.right == None) or (pre and (pre == curr.left or pre == curr.right)):
list.append(curr.val)
stack.pop()
pre = curr
else:
if curr.right:
stack.append(curr.right)
if curr.left:
stack.append(curr.left)
return list
# 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]
"""
res = []
self.dfs(root, res)
return res
def dfs(self, root, res):
if root:
self.dfs(root.left, res)
self.dfs(root.right, res)
res.append(root.val)
# 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]
"""
res = []
stack = []
pre = None
while (root or stack):
if root:
stack.append(root)
root = root.left
elif stack[-1].right != pre:
root = stack[-1].right
pre = None
else:
pre = stack.pop()
res.append(pre.val)
return res