A Java Simple Solution Based on Preorder Traversal


  • 13
    O

    Postorder traversal, which is in Left-Right-Root order. We can observe that the preorder traversal is in Root-Left-Right order, which means if we swap the order of left and right subtree when pushing into stack, we'll get Root-Right-Left, a new traversal.

    It is just the opposite way of postorder one. And that's why the following code works.

    public class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        LinkedList<Integer> result = new LinkedList<Integer>();
        if(root == null) return result;
        
        Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.push(root);
        
        while(!stack.isEmpty()){
            root = stack.pop();
            result.addFirst(root.val);
            if(root.left != null){
                stack.push(root.left);
            }
            if(root.right != null){
                stack.push(root.right);
            }
        }
        
        return result;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.