0
votes

Doing this problem: https://leetcode.com/problems/kth-smallest-element-in-a-bst/

Solution:

    Stack<TreeNode> stack = new Stack<>();      
    while(root != null || !stack.isEmpty()) {          
        while(root != null) {              
            stack.push(root);                  
            root = root.left;             
        }           
        root = stack.pop();          
        if(--k == 0) break;          
        root = root.right;      
    }      
    return root.val;  }

Example Walkthrough: https://repl.it/@Stylebender/Kth-Smallest-BST

Just wondering why the answer I get from my walkthrough (5) doesn't seem to be correct answer(4).
1
You are asking a question about a test case you haven;t posted. - Jon Guiton
Hi Sorry, there's a repl link in my initial post? Ive put it there due to the length of the walkthrough... - Mike Chan

1 Answers

0
votes

The problem is, the code you pasted here is doing pre-decrement and the code in your workspace is doing post-decrement.

If you want the result in 0-based index you need to use pre-decrement and opposite for 1-based index.