Skip to content

Commit c05fff0

Browse files
committed
Binary Tree Postorder Traversal
1 parent 2aad026 commit c05fff0

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
'''
2+
Given a binary tree, return the postorder traversal of its nodes' values.
3+
4+
For example:
5+
Given binary tree {1,#,2,3},
6+
1
7+
\
8+
2
9+
/
10+
3
11+
return [3,2,1].
12+
13+
Note: Recursive solution is trivial, could you do it iteratively?
14+
'''
15+
16+
# Definition for a binary tree node.
17+
# class TreeNode(object):
18+
# def __init__(self, x):
19+
# self.val = x
20+
# self.left = None
21+
# self.right = None
22+
23+
class Solution(object):
24+
def postorderTraversal(self, root):
25+
"""
26+
:type root: TreeNode
27+
:rtype: List[int]
28+
"""
29+
if not root:
30+
return []
31+
result = []
32+
stack = [(root, 'visit')]
33+
while stack:
34+
node, label = stack.pop()
35+
if label == 'visit':
36+
stack.append((node, 'get'))
37+
if node.right:
38+
stack.append((node.right, 'visit'))
39+
if node.left:
40+
stack.append((node.left, 'visit'))
41+
else:
42+
result.append(node.val)
43+
return result
44+
45+
46+
if __name__ == "__main__":
47+
None

0 commit comments

Comments
 (0)