【问题标题】:Computing rank of a node in a binary search tree计算二叉搜索树中节点的秩
【发布时间】:2014-09-28 01:58:11
【问题描述】:

如果二叉搜索树中的每个节点都存储其权重(其子树中的节点数),那么在我搜索时计算给定节点(其在排序列表中的索引)的排名的有效方法是什么在树上?

【问题讨论】:

    标签: algorithm tree binary-search-tree


    【解决方案1】:

    从零开始排名。随着二分搜索从根向下进行,添加搜索跳过的所有左子树的大小,包括找到的节点的左子树。

    即,当搜索向左(从父项到左子项)时,它没有发现小于搜索项的新值,因此排名保持不变。当它向右时,父节点加上左子树中的所有节点都小于搜索项,所以加一加左子树大小。当它找到搜索的项目时。包含该项目的节点的左子树中的任何项目都小于它,因此将其添加到排名中。

    把这一切放在一起:

    int rank_of(NODE *tree, int val) {
      int rank = 0;
      while (tree) {
        if (val < tree->val) // move to left subtree
          tree = tree->left;
        else if (val > tree->val) {
          rank += 1 + size(tree->left);
          tree = tree->right;
        }
        else 
          return rank + size(tree->left);
      }
      return NOT_FOUND; // not found
    }
    

    这将返回从零开始的排名。如果你需要从 1 开始,那么将 rank 初始化为 1 而不是 0。

    【讨论】:

    • 这太棒了!
    • 您的解决方案简单明了。我尝试通过保持每个节点的所有子节点计数来解决这个问题。相反,这很复杂并且容易出错,像您一样保持左子树的大小要容易得多。谢谢!
    【解决方案2】:

    由于每个节点都有一个存储其权重的字段,首先您应该实现一个方法调用 size(),它返回节点子树中的节点数:

    private int size(Node x)
    {
    if (x == null) return 0;
    else return x.N;
    } 
    

    那么计算给定节点的等级很容易

    public int rank(Node key)
    { return rank(key,root) }
    
        private int rank(Node key,Node root)
        {
            if root == null 
                 return 0;
            int cmp = key.compareTo(root);
    // key are smaller than root, then the rank in the whole tree
    // is equal to the rank in the left subtree of the root.
            if (cmp < 0) {
                return rank(key, root.left) 
            } 
    //key are bigger than root,the the rank in the whole tree is equal
    // to the size of subtree of the root plus 1 (the root) plus the rank 
    //in the right sub tree of the root.
            else if(cmp > 0){
                return size(root.left) + 1 + rank(key,root.right); 
            } 
    // key equals to the root, the rank is the size of left subtree of the root
            else return size( root.left);  
        }
    

    【讨论】:

    • 最后一个else 不正确。只有根的左子树包含小于搜索值的项目。
    【解决方案3】:

    取决于 BST 的实现,但我相信你可以递归地解决它。

    public int rank(Key key){
        return rank(root, key);
    }
    
    private int rank(Node n, Key key){
        int count = 0;
        if (n == null)return 0;
        if (key.compareTo(n.key) > 0) count++;
        return count + rank(n.left, key) + rank(n.right, key);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-23
      • 1970-01-01
      • 2020-08-07
      • 2014-05-10
      • 2015-05-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多