【问题标题】:Red black tree red children property check红黑树红孩子财产检查
【发布时间】:2012-11-30 16:22:08
【问题描述】:

给定一个 RB 树,我需要编写一个算法来检查每个红色节点的子节点是否都是黑色的。

即如果每个红色节点只有黑色子节点,则返回 true,否则返回 false。

这是我的尝试:

ChildCheck(x){
    if (x.color==black){
        if(x.leftChild !=null or x.leftchild!=nil)
            bool a = ChildCheck(x.leftChild)
        else  a = true
        if (x.rightChild!=null or x.leftchild!=nil){
            bool b = Childcheck(x.leftChild)
        else b = true
        return (a && b)
    }
    else
        if (x.leftChild !=null or x.leftchild!=nil)
            if(x.leftChild.color==black)
                d = true
            else d = false
        else
            d = true
        if (x.rightChild !=null or x.rightchild!=nil)
            if(x.rightChild.color==black)
                e = true
            else e = false
        else
            e = true
        return (d && e)
    }
}

这会返回正确的答案吗?如果没有,有什么问题?

【问题讨论】:

  • 你的问题到底是什么?
  • 我不知道如何让问题更清楚,伙计抱歉...
  • 改写 - 你要求我们对你的代码做什么?我们不太可能在这里给你答案。您希望我们检查您的代码并找出问题所在吗?如果是这样,请向我们证明您至少已经做出了基本的努力来找出您的代码有什么问题(如果有的话)。
  • 我想验证是我正在寻找的......

标签: algorithm data-structures recursion red-black-tree


【解决方案1】:
bool CheckRedProperty(NodePtr root)
{
    if (root == NULL) 
        return true;

    if (!CheckRedProperty(root->left))
        return false;

    if (CheckRedProperty(root->right))
        return false;

    if (root->IsRed() 
        && (root->left && root->left->IsRed() || root->right && root->right->IsRed()))
            return false;
    return true;
}

【讨论】:

    猜你喜欢
    • 2013-03-18
    • 2010-09-06
    • 1970-01-01
    • 2016-06-26
    • 2011-02-04
    • 2018-10-10
    • 2011-03-11
    • 2011-08-23
    • 2012-06-03
    相关资源
    最近更新 更多