Kth Smallest Element in a BST
Input: root = [3,1,4,null,2], k = 1
3
/ \
1 4
\
2
Output: 1Input: root = [5,3,6,2,4,null,null,1], k = 3
5
/ \
3 6
/ \
2 4
/
1
Output: 3Last updated
Input: root = [3,1,4,null,2], k = 1
3
/ \
1 4
\
2
Output: 1Input: root = [5,3,6,2,4,null,null,1], k = 3
5
/ \
3 6
/ \
2 4
/
1
Output: 3Last updated
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* int left;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
*
* }
*/
class Solution {
public int kthSmallest(TreeNode root, int k) {
//first thought was inorder traversal
if(root == null)
return -1;
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
while(cur != null || !stack.isEmpty()){
while(cur != null){
stack.push(cur);
cur = cur.left;
}
cur = stack.pop();
k--;
if(k == 0)
return cur.val;
cur = cur.right;
}
return -1;
}
}/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int kthSmallest(TreeNode root, int k) {
if(root == null){
return -1;
}
Map<TreeNode, Integer> map = new HashMap<>();
countNode(root,map);
return quickSelect(root, map, k);
}
public int countNode(TreeNode root, Map<TreeNode, Integer> map ){
if(root == null)
return 0;
int left = countNode(root.left, map);
int right = countNode(root.right, map);
map.put(root, left+right+1);
return left+right+1;
}
public int quickSelect(TreeNode root, Map<TreeNode,Integer> map, int k){
if(root == null)
return -1;
int left = root.left == null ? 0 : map.get(root.left);
if(left >= k){
return quickSelect(root.left, map,k);
}
if(left +1 == k){
return root.val;
}
return quickSelect(root.right, map, k - left - 1);
}
}