Simple Java with stack & visitedNode


  • 0
    V

    public class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
    Stack<TreeNode> stack = new Stack<>();
    List<Integer> result = new ArrayList<>();
    if (root != null)
    stack.push(root);

        TreeNode visitedNode = root;
        
        while (!stack.isEmpty()) {
            TreeNode node = stack.peek();
            if (node.left == null && node.right == null) {
                result.add(node.val);
                visitedNode = stack.pop();
            } else {
                if (visitedNode == node.right || visitedNode == node.left) {
                    result.add(node.val);
                    visitedNode = stack.pop();
                    continue;
                }
                if (node.right != null)
                    stack.push(node.right);
                if (node.left != null) {
                    stack.push(node.left);
                }
            }
    
        }
        return result;
    
    }
    

    }


Log in to reply
 

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