题目
Given a binary search tree, write a function kthSmallest
to find thekth smallest element in it.
Note:
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.
Follow up:
What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?
题意
给定一个二叉搜索树,通过一个方法kthSmalllest 来知道第k 小的元素。(注意题目中的假设)
分析及代码
方法1(全局计数器):
- 【二叉搜索树的定义及特点】
二叉排序树或者是一棵空树,或者是具有下列性质的 二叉树:(1)若左子树不空,则左子树上所有结点的值均小于或等于它的 根结点的值;(2)若右子树不空,则右子树上所有结点的值均大于或等于它的根结点的值;(3)左、右子树也分别为二叉排序树;
- 【特点的运用】从小到大排列 ---> 中序遍历 ;从大到小排列 --> 中序遍历 + 栈(或者以右子树开始,进行中序遍历)
- 【参数分析】观察可知,方法的参数有两个,其中一个用来表示TreeNode(提供遍历的必要),k 用来说明限制,也告诉了我们的目标。
- 【返回值】最终的结果。我们需要在遍历达到目标的时候,不断从调用层次深处到顶层传递。(可能在调用底层某个点就已经达到目标了,返回时需保持)
- 【全局计数器】计数,&& count 与 k构成限制条件。
public class KthSmallest {
int count = 0;
public int kthSmallest(TreeNode root, int k) {
TreeNode tgt = findTreeNode(root, k);
return tgt.val;
}
public TreeNode findTreeNode(TreeNode root,int k){
if(root == null) return null;
TreeNode left = findTreeNode(root.left, k);
if(count == k) return left;
if(++count == k) return root;
return findTreeNode(root.right, k);
}
}
反例:
下面程序也正确,只不过有大量重复操作。(体现在countNodes处)(原程序地址)
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); // 1 is counted as current node
}
return root.val;
}
public int countNodes(TreeNode n) {
if (n == null) return 0;
return 1 + countNodes(n.left) + countNodes(n.right);
}