Clean Iterative approach in Java


  • 0
    L
       public List<Integer> inorderTraversal(TreeNode root) {
            List<Integer> list = new ArrayList<Integer>();
            if(root==null) {
                return list;
            }
            Stack<TreeNode> stack = new Stack<>();
            while(root!=null) {
                stack.push(root);
                root=root.left;
            }
            
            while(!stack.isEmpty()) {
                TreeNode temp = stack.pop();
                System.out.println(temp.val);
                list.add(temp.val);
                TreeNode right = temp.right;
                if(right!=null) {
                    stack.push(right);
                    TreeNode left = right.left;
                    while(left!=null) {
                        stack.push(left);
                        left = left.left;
                    }
                }
            }
            return list;
        }
    

Log in to reply
 

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