第一次看到这道题的想法是利用二分搜索树的特性来做题:
(1)若左子树不空,则左子树上所有节点值均小于或等于它的根节点值;
(2)若右子树不空,则右子树上所有节点值均大于或等于它的根节点值;
(3)左、右子树也为二叉搜索树;
根据特性,如果按中序遍历来遍历BST,就可以得到从小到大的节点,那么我们设一个counter,每遍历一个节点就++,等到counter等于k-1的时候,就return并返回当前节点的val,就是正确答案
public class Solution {
/**
* @param root: the given BST
* @param k: the given k
* @return: the kth smallest element in BST
*/
int counter = 0;
int value = 0;
public int kthSmallest(TreeNode root, int k) {
findKth(root,k);
return value;
}
public void findKth(TreeNode root, int k){
if(root == null) return;
findKth(root.left,k);
if(counter == k) return;
counter++;
value = root.val;
findKth(root.right,k);
}
}