【问题标题】:Insert into Red Black Tree插入红黑树
【发布时间】:2018-11-06 18:11:50
【问题描述】:

我想递归地插入一个新节点,然后从函数 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 正常工作的同时做到这一点?现在,如果我不从insertRec 返回current,那么我将无法正确创建树。

【问题讨论】:

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


    【解决方案1】:

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

    通常对于红黑树,您以线性方式而不是递归方式进行插入。比如:

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

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

    【讨论】:

      猜你喜欢
      • 2013-11-17
      • 2018-05-30
      • 1970-01-01
      • 2017-12-23
      • 2013-02-28
      • 2011-08-06
      • 1970-01-01
      • 2013-06-12
      相关资源
      最近更新 更多