我们要判断一棵二叉树是不是红黑树,最直接的方法就是看二叉树是否满足红黑树的5条性质,这5条性质在上一篇红黑树中提到。
bool _IsBRTree(PNode PRoot)
{
if (PRoot == NULL)
return true;
if (PRoot->_color == RED)
return false;
int count = 0;//统计一条路径上黑节点的个数
int num = 0;//其他路径黑结点的个数
PNode pcur = PRoot;
while (pcur)
{
if (pcur->_color == BLACK)
count++;
pcur = pcur->_PLeft;
}
return _Check(PRoot, count, num);
}
bool _Check(PNode pRoot, int count, int num)
{
if (pRoot == NULL)
return true;
PNode pcur = pRoot;
if (pcur->_color == RED && pcur->_Pparent && pcur->_Pparent->_color == RED)
{
cout << "有连续的红结点" << endl;
return false;
}
if (pcur->_color == BLACK)
num++;
if (pcur->_PLeft == NULL&&pcur->_PRight == NULL)
{
if (count == num)
return true;
else
{
cout << "黑色结点的个数不一样!" << endl;
return false;
}
}
return _Check(pcur->_PLeft, count, num) && _Check(pcur->_PRight, count, num);
}