简体   繁体   English

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

[英]Nth largest node in Binary Search Tree

I'm trying to find the Nth largest node in a Binary Search Tree given a number. 我试图在给定数字的二分搜索树中找到第N个最大的节点。 All other solutions online find the Nth smallest node such as this one: 在线上所有其他解决方案都找到第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; 
} 

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

How would I convert the select(Node x, int k) method to find the Nth largest node? 如何转换select(Node x,int k)方法以找到第N个最大节点?

For example, in a BST that looks like: 例如,在如下所示的BST中:

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

The largest node has a key of 40. 最大节点的密钥为40。

The Ranked BST would look like: 排名BST看起来像:

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

One thing to note about this BST is that the rank starts from 0. 关于此BST的一件事要注意的是,等级从0开始。

A simpler way 更简单的方法

For a BST containing X elements numbered 0 to (X-1) , 对于包含编号为0(X-1) X元素的BST,

The Nth smallest element is equivalent to the (XN)th largest element, and vice versa. Nth最小元素等于第(XN)th最大元素,反之亦然。

If you have no choice but to change the method 如果您别无选择,只能更改方法

What select does in this case is something like a binary search on the rank. 在这种情况下,select的作用类似于在等级上进行二进制搜索。 So if we adjust it such that it always goes towards the right for smaller ranks (and left for higher ranks), we can make it to return the answer we want. 因此,如果我们对其进行调整,使其对于较小的等级始终朝右(对于较高的等级朝左),则可以使其返回所需的答案。

Invert the x.right and x.left : 反转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