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

问题:

给一个二叉查找树(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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值