/** The following function checks the red black tree black height
* @param n the root node is inputed then a traversal is done to calculate the black-height
* @return Return an error message / mesages informing the user whether or not the black height was maintained
* @author Ferron Smith
*/

public static void getCount (SkaRedBlackTreeNode skaRedBlackTreeNode) {
    VizRedBlackTreeNode n = skaRedBlackTreeNode.getVizRep();
if (validRoot(n))
    {
        static int lcount = leftCount(n);
        static int rcount = rightCount(n);

        if (rcount == lcount) {
            n.displayMsg("Black height maintained");
        }
        else
            // n.displayWarning("rcount " + rcount + " lcount " + lcount);
            n.displayError("Red Black Tree is unbalanced");
    }
}

/** The following function counts all the black node of the left side of the tree
 * @param n the left child is inputed and a traversal is done to count all the black nodes
 * */
public static int leftCount (VizRedBlackTreeNode n)
{
        if (n == null)
        return 0;
        else if (n.getrbtColr() == Color.black) 
                return 1 + leftCount(n.getLeft());
        else 
            leftCount(n.getLeft());    
}

/** The following function counts all the black node of the right side of the tree
 * @param n the right child is inputed and a traversal is done to count all the black nodes
 * */
public static int rightCount (VizRedBlackTreeNode n)
{   
    if (n == null)
    return 0;
    else if (n.getrbtColr() == Color.black) {
            return 1 + rightCount (n.getRight());
    else    
        rightCount(n.getRight());
    }
}

这是改写,你觉得这个一会的工夫,我已经测试过它在一定条件下,并不会让我失望尚未

有帮助吗?

解决方案

据我所知,你只能在这树的最左和最右路径检查黑的高度。红 - 黑树的定义要求黑高度上的所有的路径是相同的。例如,该无效树不是由程序标记:

      B
     / \
    /   \
   /     \
  B       B
 / \     / \
B   R   R   B

此外,它不检查周期或如果键是为了

其他提示

所以,我意识到你在Java工作在这里,但这里的一些伪代码,可以帮助:

unsigned int blackHeight()
  height, heightLeft, heightRight = 0
  if black
    height++
  if left
    heightLeft = left->blackHeight()
  else
    heightLeft = 1
  if right
    heightRight = right->blackHeight()
  else
    heightRight = 1
  if heightLeft != heightRight
    //YOU HAVE A PROBLEM!
  height += heightLeft
  return height

我只是刚开始使用红黑树进行试验,不过我相信这个算法应该给你你从调用它的任何节点上的黑色高度。

编辑:我想我应该有资格,这不是在树中的一个节点内发现的是代码。在C ++中,它将与一个someNode-> blackHeight()被调用。

 //enter code here

    private static void blackHeight(rbnode root) {
        if (root == null)
            return; 

        if (root.color == "black") {
            root.black_count = root.parent.black_count+1;

        } else {
            root.black_count = root.parent.black_count;
        }
        if ((root.left == null) && (root.right == null)) {              
            bh = root.black_count;              
        }               
        blackHeight(root.left);
        blackHeight(root.right);
    } 
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top