Suggestion requested for my solution


  • 0
    H

    Re: Iterative solution in Java - simple and readable

    Hello Friends, I have a similar solution but I didn't want to check for cur!=null and thus came with below solution. For [1,null,2,3] my iterative solution keep inserting left child 3 after 2. I am not able to figure out how should I minimally change my code to mark a left node that it has been processed. Suggestions?

    public List<Integer> inorderTraversal(TreeNode root) {
            List<Integer> l = new ArrayList<>();
            if(root == null) return l;
            
            LinkedList<TreeNode> stack = new LinkedList<>();
            stack.addLast(root);
            
            while(!stack.isEmpty()){
                TreeNode cur = stack.peekLast();
                
                while(cur.left!=null){
                    stack.addLast(cur.left);
                    cur = cur.left;
                }
                cur = stack.removeLast();
                l.add(cur.val);
                if(cur.right!=null){stack.addLast(cur.right);}
            }
            return l;
        }
    

Log in to reply
 

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