红黑树<black height =“”>(Redraft)</black>

时间:2009-05-26 07:50:49

标签: java tree red-black-tree

/** 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());
    }
}

这是重写,你认为这个会起作用,我已经在某些条件下测试了它并且没有让我失望

3 个答案:

答案 0 :(得分:4)

所以我意识到你在这里工作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-&gt; blackHeight()来调用。

答案 1 :(得分:1)

据我所知,你只是在树下最左边和最右边的路径上检查黑色高度。红黑树的定义要求所有路径上的黑色高度相同。例如,您的程序不会标记此无效树:

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

此外,它不会检查周期或键是否有序。

答案 2 :(得分:1)

 //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);
    }