Accepted Java solution. Use null as a mark.


  • 1
    G

    public List<Integer> postorderTraversal(TreeNode root) {
    List<Integer> ans = new ArrayList<Integer>();
    if (root == null)
    return ans;
    Stack<TreeNode> stack = new Stack<TreeNode>();
    stack.push(root);
    while (!stack.isEmpty()) {
    TreeNode node = stack.pop();
    if (node != null) {
    stack.push(node);
    stack.push(null);
    if (node.right != null)
    stack.push(node.right);
    if (node.left != null)
    stack.push(node.left);
    } else {
    node = stack.pop();
    ans.add(node.val);
    }
    }
    return ans;
    }


Log in to reply
 

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