问题:
给一个二叉查找树(BST),找出第 k 大的值。比如:
该图中,第3大的值是10.
分析:
我们可以通过类似中序遍历的方法把BST从大到小排序,然后,就可以得到第 k 大的值了。代码如下:
public class NthNode {
// k refers to the counter. it is a global variable.
static int k = 0;
//get the nth largest value in BST
public void getNthnode(Node root, int n) {
if (root == null) return;
getNthnode(root.rightChild, n);
k++;
if (k == n) {
System.out.print(root.toString());
return;
}
getNthnode(root.leftChild, n);
}
}
class Node {
Node leftChild = null;
Node rightChild = null;
int value;
Node(int value) {
this.value = value;
}
public String toString() {
return value + "";
}
}
http://blog.csdn.net/beiyeqingteng