繁体   English   中英

二进制搜索树中的第N个最大节点

[英]Nth largest node in Binary Search Tree

我试图在给定数字的二分搜索树中找到第N个最大的节点。 在线上所有其他解决方案都找到第N个最小的节点,例如:

/**
 * Return the key in the symbol table whose rank is {@code k}.
 * This is the (k+1)st smallest key in the symbol table.
 *
 * @param  k the order statistic
 * @return the key in the symbol table of rank {@code k}
 * @throws IllegalArgumentException unless {@code k} is between 0 and
 *        <em>n</em>–1
 */
public Key select(int k) {
    if (k < 0 || k >= size()) {
        throw new IllegalArgumentException("argument to select() is invalid: " + k);
    }
    Node x = select(root, k);
    return x.key;
}

// Return key of rank k. 
private Node select(Node x, int k) {
    if (x == null) return null; 
    int t = size(x.left); 
    if      (t > k) return select(x.left,  k); 
    else if (t < k) return select(x.right, k-t-1); 
    else            return x; 
} 

资料来源: https : //algs4.cs.princeton.edu/32bst/BST.java.html

如何转换select(Node x,int k)方法以找到第N个最大节点?

例如,在如下所示的BST中:

       30
     /    \
    20    35
   / \    / \
 15   25 31 40

最大节点的密钥为40。

排名BST看起来像:

        4
     /    \
    6      2
   / \    / \
  7   5  3   1

关于此BST的一件事要注意的是,等级从0开始。

更简单的方法

对于包含编号为0(X-1) X元素的BST,

Nth最小元素等于第(XN)th最大元素,反之亦然。

如果您别无选择,只能更改方法

在这种情况下,select的作用类似于在等级上进行二进制搜索。 因此,如果我们对其进行调整,使其对于较小的等级始终朝右(对于较高的等级朝左),则可以使其返回所需的答案。

反转x.rightx.left

private Node select(Node x, int k) {
    if (x == null) return null; 
    int t = size(x.right); 
    if      (t > k) return select(x.right,  k); 
    else if (t < k) return select(x.left, k-t-1); 
    else            return x; 
} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM