145. Binary Tree Postorder Traversal

Link

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

由於root node會是最後travel,那麼透過add(0, node.val)的方式,保證先travel的會在list的最後面 接下來就是保證想先travel的節點先丟到stack, 1. node.left先放入stack 2. 接下來再放node.right

 public List<Integer> postorderTraversal(TreeNode root) {     
        List<Integer> ret = new LinkedList<>();
        if(root == null) return ret;
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        
        while(!stack.isEmpty()){
            TreeNode node = stack.pop();
            ret.add(0, node.val);
            if(node.left != null){
                stack.push(node.left);
            }
            if(node.right != null){
                stack.push(node.right);    
            } 
        
        }
        return ret;
    }

Last updated

Was this helpful?