Iterative Inorder Trasversal

94. Binary Tree Inorder Traversal


class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> result = new LinkedList<>();
        Stack<TreeNode> stack = new Stack<>();
        while(root!=null || !stack.isEmpty()){
            //push all the way to the left leaf
            while(root!=null){
                stack.push(root);
                root=root.left;
            }
            root = stack.pop();
            result.add(root.val);
            root = root.right;
        }
        return result;
    }
}

Last updated