I am trying to search all the root-to-leaf paths within a given red black tree. In particular, I was wanting to write a test that, given a rbt, will assert that every path has the same count of black nodes.
I was trying something like this with two global variables:
static int count = 0, path = -1;
int check_paths(tree_node t)
{
if (t == NULL)
{
if (path == -1)
path = count;
else
return (path == count);
return 1;
}
if (t->black == 1) ++count;
int x,y;
x = check_paths(t->left);
if (t->black == 1) --count;
y = check_paths(t->right);
return (x&&y);
}
however, I was having trouble with cases when there were red nodes to the right of black nodes in left branches since this would mean that the count was decremented more than it should be.
Is there a better way to search root-to-leaf paths and count the frequency of a particular value and then compare the counts somehow? Or alternatively, is there a completely different method for testing a rbt's balance if given one (i.e. it is already made but the correctness of it is uncertain)?