【问题标题】:Can someone please verify if RedBlack Tree successor is written correctly?有人可以验证红黑树后继者是否正确编写?
【发布时间】:2011-04-14 20:24:44
【问题描述】:
pair<K,V> *RedBlackTree<K,V,Compare>::successor(K key) {

    Node *found = findNode(key, root);

    Node *p;
    Node *ch;
    Node *x;

    Node *y;
    if(found->right != sentinel)
        return new pair<K,V>(found->right->key, found->right->value);

    y = found->parent;
    /* if it does not have a left child,
    predecessor is its first left ancestor */
    while(y != NULL && found == y->right) {
            found = y;
            y = y->parent;
    }
    return new pair<K,V>(y->key, y->value);



}

【问题讨论】:

  • 也许这种问题更适合codereview.stackexchange.com
  • 你在代码审查中可能会有更好的运气:codereview.stackexchange.com
  • 神圣的动态分配,蝙蝠侠!返回指向动态分配的pair 的指针几乎肯定是错误的。您可能希望按值返回 pair。这段代码看起来不对:found-&gt;right 并不总是中序遍历中的下一个节点,因为found-&gt;right 可能有一个左子树。我发布了一个如何找到继任者in an answer to another question的示例。

标签: c++ red-black-tree


【解决方案1】:

此代码不正确。考虑以下树:

   b
  / \
 a   f
    / \
   d   g
  / \
 c   e

b 的顺序后继是c。您的函数认为有序后继是f。要找到有序的继任者,您必须处理几种情况;这个示例树有一个需要处理的每个案例的实例。从每个节点开始,写下为每个节点找到有序后继节点所需的步骤。

如果您有兴趣,可以在an answer I gave to another question 中找到该算法的实现以及完整的解释。


在不相关的说明中,您的函数几乎肯定会返回一个std::pair按值,并且您不应该动态分配std::pair

【讨论】:

    猜你喜欢
    • 2018-10-10
    • 1970-01-01
    • 2022-01-14
    • 2015-04-16
    • 2016-06-28
    • 2011-04-23
    • 2021-05-25
    • 2019-04-19
    • 2011-09-18
    相关资源
    最近更新 更多