230.Kth Smallest Element in a BST
1-BST InOrder Traversal Using Stack
class Solution {
public int kthSmallest(TreeNode root, int k) {
int cnt = 0;
int ans = 0;
Deque<TreeNode> stack = new ArrayDeque<>();
while(root != null || !stack.isEmpty()){
while(root != null){
stack.push(root);
root = root.left;
}
root = stack.pop();
cnt += 1;
if(cnt == k){
ans = root.val;
break;
}
root = root.right;
}
return ans;
}
}
2-DFS Recursive
class Solution {
public int kthSmallest(TreeNode root, int k) {
int count = countNodes(root.left);
if(k <= count){
return kthSmallest(root.left, k);
}
else if (k > count + 1){
return kthSmallest(root.right, k - 1 - count);
}
return root.val;
}
public int countNodes(TreeNode root){
if(root == null){
return 0;
}
return 1 + countNodes(root.left) + countNodes(root.right);
}
}