-
Notifications
You must be signed in to change notification settings - Fork 1
/
145-binary_tree_postorder_traversal.py
57 lines (45 loc) · 1.29 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
"""
https://leetcode.com/problems/binary-tree-postorder-traversal/
Strat:
Do recursively. Iterative needs additional space or destroying the tree.
Post : Left Right Me
4
2 5
9 3 1 6
8
9, 3, 2, 1, 8, 6, 5, 4
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
result = []
self.postorder_helper(root, result)
return result
def postorder_helper(self, root, result):
if root == None:
return
if root.left:
self.postorder_helper(root.left, result)
if root.right:
self.postorder_helper(root.right, result)
result.append(root.val)
#iterative is pretty hard, #TODO in the future
# def postorderTraversal(self, root):
# """
# :type root: TreeNode
# :rtype: List[int]
# """
# result = []
# stack = []
# curr = root
# while stack or curr:
# pass