Accepted Java solution using single Stack. No reversal.


  • 0
    M
    public List<Integer> postorderTraversal(TreeNode root) {
    
            List<Integer> res = new ArrayList<>();
            if (root == null) return res;
    
            Stack<TreeNode> s = new Stack<>();
            s.push(root);
            TreeNode curr;
    
            while (!s.isEmpty()) {
    
                curr = s.peek();
                if (curr.left != null) {
                    s.push(curr.left);
                    curr.left = null;
                }
                else if (curr.right != null) {
                    s.push(curr.right);
                    curr.right = null;
                }
                else {
                    curr = s.pop();
                    res.add(curr.val);
                }
            }
    
            return res;
        }
    }
    

    Please critique my approach. Thanks.


Log in to reply
 

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