Stupid but works, really straight forward java iterative solution.


  • 0
    M
    public List<Integer> inorderTraversal(TreeNode root) {
            List<Integer> resultInorder = new ArrayList<Integer>();
            Stack<TreeNode> NodeStack = new Stack<TreeNode>();
            if (root != null){
                NodeStack.push(root);
            }
            while(!NodeStack.empty()){
                TreeNode current = NodeStack.pop();
                if (current.left == null && current.right == null){
                    resultInorder.add(current.val);
                }
                else{
                    if (current.right != null){
                        NodeStack.push(current.right);
                        current.right = null;
                    }
                    NodeStack.push(current);
                    if (current.left != null){
                        NodeStack.push(current.left);
                        current.left = null;
                    }
                }
            }
            return resultInorder;
        }

  • 0
    X

    why you need to set current.right = null?


  • 0
    M

    so current right itself doesn't gets iterated again. I don't think we should modify the value of the nodes though. That's why I said this is a stupid solution.


  • 0
    H

    good answer, not stupid :)


Log in to reply
 

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