L145. Binary Tree Postorder Traversal

Binary Tree left right root

Problem:

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

Example:

Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [3,2,1]

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

Solution:

  • recursion

private List<Integer> res;
public List<Integer> postOrder(TreeNode root){
    res = new ArrayList<>();
    helper(root);
    return res;
}
private void helper(TreeNode root){
    if(root == null) return;
    helper(root.left);
    helper(root.right);
    res.add(root.val);
}
  • iteration:

    • do it as the order of root right left

    • reserve it so we could get left right root

public List<Integer> postOrder(TreeNode root){
    List<Integer> res = new ArrayList<>();
    if(root == null) return res;
    Stack<TreeNode> stack = new Stack<>()
    while(root != null || !stack.isEmpty()){
        if(root == null){
            root = stack.pop();
            root = root.left;
        }else{
            res.add(root.val);
            stack.push(root);
            root = root.right
        }
    }
    Collections.reverse(res);
    return res;
}

Last updated

Was this helpful?