Iterative InOrder Traversal in JAVA using Stack


  • 1
    N
    // inorder traversal
    public int kthSmallest(TreeNode root, int k) {
        Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.push(root);
        TreeNode node = root;
        int count = 0;
        // node == null, might get to the leaf but stack is not empty
        while(node!=null || !stack.isEmpty()){
            while(node!=null){
                stack.push(node);
                node = node.left;
            } 
            node = stack.pop();
            count++;
            if(count==k) return node.val;
            node = node.right;
        }
        return -1;
    }

Log in to reply
 

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