How to check the black-height of a node for all paths to its descendent leaves?

柔情痞子 提交于 2019-12-06 13:52:16

It wiil return the black height of the RB-tree. If the height is 0, the tree is an invalid red black tree.

int BlackHeight(NodePtr root)
{
    if (root == NULL) 
        return 1;

    int leftBlackHeight = BlackHeight(root->left);
    if (leftBlackHeight == 0)
        return leftBlackHeight;

    int rightBlackHeight = BlackHeight(root->right);
    if (rightBlackHeight == 0)
        return rightBlackHeight;

    if (leftBlackHeight != rightBlackHeight)
        return 0;
    else
        return leftBlackHeight + root->IsBlack() ? 1 : 0;
}

Below code verifies if number of black nodes along any path is same

#define RED 0
#define BLACK 1

struct rbt {
    int data;
    struct rbt *left;
    struct rbt *right;
    int parent_color; // parent link color
    uint64_t nodes_count; // to store number of nodes present including self
    int level; // to store level of each node
};
typedef struct rbt rbt_t;

int check_rbt_black_height(rbt_t *root)
{
    if(!root) return 1;
    else {
        int left_height  = check_black_violation(root->left);
        int right_height = check_black_violation(root->right);
        if (left_height && right_height && left_height != right_height) {
            printf("Error: Black nodes are not same @level=%d\n", root->level);
            exit(1);
        }
        if (left_height && right_height) 
                   // do not increment count for red
            return is_color_red(root) ? left_height : left_height + 1; 
        else
            return 0;
    }
}

int is_color_red(rbt_t *root)
{
    if(root && root->parent_color == RED) return 1;
    return 0;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!