问题:
给一个二叉查找树(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.youkuaiyun.com/beiyeqingteng
本文介绍了一种在二叉查找树(BST)中寻找第k大值的有效方法。通过类似中序遍历的方式,从大到小遍历BST节点,并使用计数器来确定目标节点。此算法简单高效。
366

被折叠的 条评论
为什么被折叠?



