插入红黑树

时间:2018-05-28 07:45:18

标签: java recursion binary-search-tree red-black-tree

我希望以递归方式插入新节点,然后从函数insertRec返回新插入的节点。函数调用看起来像这样

    void insert(int value) {       
       root = insertRec(root, null, value);
       root = insertRec(root, null, 15);
       root = insertRec(root, null, 6);
       root = insertRec(root, null, 5);
       root = insertRec(root, null, 3);
       root = insertRec(root, null, 4);
       //insertFixup(newNode);
    }

    RedBlackNode insertRec(RedBlackNode current, RedBlackNode prev, int value)  
    {
       if(current == null) {
         current = new RedBlackNode(value);
         current.p = prev;
       }
       else if(current.key < value) {
         current.right = insertRec(current.right, current, value);
       }
       else {
         current.left = insertRec(current.left, current, value);
       }
       return current;
    }

如何在确保insertRec正常工作的同时这样做?现在,如果我不从current返回insertRec,那么我无法正确创建树。

1 个答案:

答案 0 :(得分:0)

在您的代码中,您不会处理节点的颜色,这也很重要吗?

通常对于红黑树,您以线性方式进行插入,而不是使用递归。类似的东西:

private void insert(int value) {
        RedBlackNode parent = null;
        RedBlackNode current = root;

        while (current!=null){
            parent = current;

            if (value < current.key){
                current = x.left;
                //Here if you store the number of items on the left of a node increase it
            }           
            else{
                current = current.right;
                //Here if you store the number of items on the right  of a node increase it
            }
        }

        RedblackNode newNode=new RedBlackNode(value);

        newNode.p=parrent;

        // Here if parent is null the new node is root of the tree
        //if (parrent==null)
        //      root = newNode;  


        if (value < parent.key)
            parent.left = newNode;
        else
            parent.right = newNode;
        // Usually we add it as RED and then fix the tree to comply with red black tree rules
        newNode.color=(RED);
        fixTree(newNode);
        }

这是一些伪代码但是这个想法。您迭代树向下,直到您达到null。然后将新节点添加为RED,然后您可能需要旋转树来修复颜色。