有人可以验证RedBlack Tree后继是否写得正确吗?

时间:2011-04-14 20:24:44

标签: c++ red-black-tree

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);



}

1 个答案:

答案 0 :(得分:4)

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

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

b的有序继承者是c。您的函数认为有序后继是f。要找到有序继承者,你必须处理几个案例;此示例树具有需要处理的每个案例的实例。从每个节点开始,记下查找每个节点的有序后继所需的步骤。

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


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