c++ - 检查一棵树是否满足红黑树的black-height属性

标签 c++ c algorithm tree red-black-tree

如何递归检查给定的红黑树是否遵守“从节点到空链接的每条路径必须包含相同数量的黑节点”的规则。 我正在使用这种结构:

enum color = {RED, BLACK};

typedef struct node {
    int value;
    struct node* left;
    struct node* right;
    color c;
} node;

我已经尝试使用这个原型(prototype)来实现一个算法:

bool isRBT(struct node* tree, int numberBlackNodesLeft, int numberBlackNodesRight)

但是,我无法递归地计算这些数字。因为,该规则规定来自一个节点的每条路径都必须遵守该规则。这对我来说有些难以实现。

有什么好主意吗?

提前致谢!

最佳答案

这里有一个简单的方法:

// Returns the number of black nodes in a subtree of the given node
// or -1 if it is not a red black tree.
int computeBlackHeight(node* currNode) {
    // For an empty subtree the answer is obvious
    if (currNode == NULL)
        return 0; 
    // Computes the height for the left and right child recursively
    int leftHeight = computeBlackHeight(currNode->left);
    int rightHeight = computeBlackHeight(currNode->right);
    int add = currNode->color == BLACK ? 1 : 0;
    // The current subtree is not a red black tree if and only if
    // one or more of current node's children is a root of an invalid tree
    // or they contain different number of black nodes on a path to a null node.
    if (leftHeight == -1 || rightHeight == -1 || leftHeight != rightHeight)
        return -1; 
    else
        return leftHeight + add;
}

要测试一棵树是否满足红黑树的black-height属性,可以把上面的函数包装成:

bool isRBTreeBlackHeightValid(node* root)
{
    return computeBlackHeight(root) != -1;
} 

关于c++ - 检查一棵树是否满足红黑树的black-height属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27731072/

相关文章:

vb.net - 可能的设计模式建议?

algorithm - 检查一个单词是否由一个或多个串联的字典单词组成

带有用户输入的 C++ gethostbyaddr

java - 声音处理 - Android 上的节拍匹配音乐播放器

c - 在 void 指针的指针值处赋值

c - for (unsigned char i = 0; i<=0xff; i++) 产生无限循环

c - 初始化新的哈希表,指针问题

java - 该算法的时间复杂度是多少?

c++ - 二叉搜索树插入

c++ - 来自不同命名空间的 std::vector push_back 类