Without reverse or insertion, a standard Java solution.


  • 0
    N
    public List<Integer> postorderTraversal(TreeNode root) {
            List<Integer> result = new LinkedList<>();
            Stack<TreeNode> stack = new Stack<>();
            TreeNode curr = root;
            while(curr != null || !stack.isEmpty()){
                while(curr != null){
                    stack.push(curr);
                    if(curr.left != null){
                        curr = curr.left;
                    }else{
                        curr = curr.right;
                    }
                }
                curr = stack.pop();
                result.add(curr.val);
                
                if(!stack.isEmpty() && stack.peek().left == curr){
                    curr = stack.peek().right;
                }else{
                    curr = null;
                }
            }
            return result;
        }
    
    

Log in to reply
 

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