intuitive iterative solution in Java


  • 0
    H
    1. write your recursive pseudo code
    2. simulate the stack during recursive call
    class Solution {
        public List<Integer> postorderTraversal(TreeNode root) {
            List<Integer> postorder = new ArrayList<>();
            Stack<TreeNode> stack = new Stack<>();
            Stack<Boolean> stackFlag = new Stack<>();
            if(root == null) return postorder;
            stack.push(root);
            stackFlag.push(false);
            while(stack.isEmpty() == false){
                TreeNode top = stack.peek();
                boolean visited = stackFlag.peek();
                if(!visited){
                    stackFlag.pop();
                    stackFlag.push(true);
                    if(top.right != null){
                        stack.push(top.right);
                        stackFlag.push(false);
                    }
                    if(top.left != null){
                        stack.push(top.left);
                        stackFlag.push(false);
                    }
                }else{
                    top = stack.pop();
                    stackFlag.pop();
                    postorder.add(top.val);
                }
            }
            return postorder;
        }
    }
    

Log in to reply
 

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