Input: [1,null,2,3]
1
\
2
/
3
Output: [3,2,1]
class Solution:
def postorderTraversal(self, root: TreeNode) -> List[int]:
return self.postorderTraversal(root.left) + self.postorderTraversal(root.right) + [root.val] if root else []
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 递归法
def postorderTraversal(self, root: TreeNode) -> List[int]:
def helper(root, res):
if not root: return res
helper(root.left, res)
helper(root.right, res)
res.append(root.val)
return res
res = helper(root, [])
return res
# 迭代法
def postorderTraversal(self, root: TreeNode) -> List[int]:
stack, res = [], []
while root or stack:
if root:
res.append(root.val)
stack.append(root)
root = root.right
else:
root = stack.pop()
root = root.left
return res[::-1]