Given a red-black tree, I need to write an efficient algorithm that checks whether for each node, all paths from from the node to descendant leaves contain the same number of black nodes, i.e. the algorithm should return a boolean if the property is true or false otherwise.
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;
}
来源:https://stackoverflow.com/questions/13848011/how-to-check-the-black-height-of-a-node-for-all-paths-to-its-descendent-leaves