Java solution use visited flag with only one stack


  • 0
    H

    '''

    public class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        if (root == null) return res;
        Stack<TreeNode> stk = new Stack<TreeNode>();
        TreeNode lastv = null;
        
        while (!stk.isEmpty() || root != null){
            while (root != null){
                stk.push(root);
                root = root.left;
            }
            root = stk.peek();
            if (root.right != null && lastv != root.right) root = root.right;
            else{
                res.add(root.val);
                lastv = stk.pop();
                root = null;
            }
        }
        return res;
    }
    

    }
    '''


Log in to reply
 

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