145. binary tree postorder traversal 解法

145. Binary Tree Postorder Traversal

Difficulty: Hard

Given a binary tree, return the postorder traversal of its nodes’ values.

Example:

1
2
3
4
5
6
7
8
Input: [1,null,2,3]
1

2
/
3

Output: [3,2,1]

Follow up: Recursive solution is trivial, could you do it iteratively?

解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class :
def postorderTraversal(self, root: TreeNode) -> List[int]:
ans = []
if root == None:
return []
st = [root]
while len(st) != 0:
node = st.pop()
ans.append(node.val)
if node.left:
st.append(node.left)
if node.right:
st.append(node.right)
return ans[::-1]