首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >插入红黑树

插入红黑树
EN

Stack Overflow用户
提问于 2018-05-28 07:45:18
回答 1查看 712关注 0票数 0

我想递归地插入一个新节点,然后从函数insertRec返回新插入的节点。函数调用如下所示

代码语言:javascript
复制
    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,那么我就无法正确地创建树。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-05-28 08:08:26

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

通常,对于红黑树,插入是线性的,而不是递归的。类似于:

代码语言:javascript
复制
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为止。然后将新节点添加为红色,然后可能需要旋转树来修复颜色。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50561471

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档