Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree.
Example 1:
Input: root = [3,1,4,null,2], k = 1
Output: 1
Example 2:
Input: root = [5,3,6,2,4,null,null,1], k = 3
Output: 3
Recursive:
class Solution {
int count = 0;
int result = Integer.MIN_VALUE;
public int kthSmallest(TreeNode root, int k) {
traverse(root, k);
return result;
}
public void traverse(TreeNode root, int k) {
if(root == null) return;
traverse(root.left, k);
count ++;
if(count == k) result = root.val;
traverse(root.right, k);
}
}
Time: O(n) Space: O(n)
Iterative:
class Solution {
public int kthSmallest(TreeNode root, int k) {
Stack<TreeNode> stack = new Stack<TreeNode>();
int count = 0;
while(!stack.isEmpty() || root != null) {
if(root != null) {
stack.push(root); // Just like recursion
root = root.left;
} else {
TreeNode node = stack.pop();
if(++count == k) return node.val;
root = node.right;
}
}
return Integer.MIN_VALUE;
}
}
class Solution {
public int kthSmallest(TreeNode root, int k) {
Stack<TreeNode> stack = new Stack<TreeNode>();
while (true){
while (root != null){
stack.push(root);
root = root.left;
}
root = stack.pop();
if (--k == 0) return root.val;
root = root.right;
}
}
}