c++ - c语言 指针问题
阿神
阿神 2017-04-17 13:51:46
0
1
515

对有两个节点的二叉树右旋时出错(根节点key为8,左子树key为5),想对8右旋,运行到注释哪里就出问题了,希望root->parent指向的地址改为root_old->parent指向的地址,但是被指针弄晕了,当前root->parent指向的是root本身,执行过后就变成root就变null了,麻烦大家看看,帮我弄清楚

运行前后截图:

    struct node
    {
        T key;
        node *left, *right,*parent;
    }*root;


    void rotateR(node *&root)
    {
        node *root_old = root;    
        root = root->left;
        root_old->left = root->right;
        root->right= root_old;
        root->parent= root_old->parent; //
        root_old->parent=root;
        root_old->left->parent = root_old;
    }

    void splay(node *n)
    {
        。。。。
    }


};
阿神
阿神

闭关修行中......

reply all(1)
黄舟

Give me a right-hand python implementation, and you should be able to see the problem by comparing yours.
x is equivalent to yours. old root
y is equivalent to root

    def __right_rotate(self, x):
        if not x.left:
            raises('cannot rotate from nil')
        y = x.left
        x.left = y.right
        if y.right:
            y.right.parent = x
        y.parent = x.parent
        if not x.parent:
            self.root = y
        elif x.is_left():
            x.parent.left = y
        else:
            x.parent.right = y
        y.right = x
        x.parent = y
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!