您的位置:首页 > 其它

找出二叉查找树中第n大的值

2012-04-22 03:53 162 查看
问题:

给一个二叉查找树(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());
}
getNthnode(root.leftChild, n);
}

public static void main(String[] args) {
Node a = new Node(8);
Node b = new Node(3);
Node c = new Node(10);
Node d = new Node(1);
Node e = new Node(6);
Node f = new Node(14);
Node g = new Node(4);
Node h = new Node(7);
Node i = new Node(13);

a.leftChild = b;
a.rightChild = c;
b.leftChild = d;
b.rightChild = e;
c.rightChild = f;
e.rightChild = g;
e.rightChild = h;
f.leftChild = i;
//the third largest value in BST
new NthNode().getNthnode(a, 3);
}
}

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  null string class c