-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path145.py
59 lines (50 loc) · 1.28 KB
/
145.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
#!/usr/bin/env python
# coding=utf-8
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# recursive version
class Solution1(object):
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
ans = []
def dfs(node):
if not node:
return
dfs(node.left)
dfs(node.right)
ans.append(node.val)
return
dfs(root)
return ans
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# iterative version
class Solution(object):
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
ans, stack = [], [root]
stack = [root]
while stack:
top = stack.pop()
if top:
ans.append(top.val)
stack.append(top.left)
stack.append(top.right)
return ans[::-1]
if __name__ == '__main__':
s = Solution()
print s.postorderTraversal([])