删除AVL树中的节点

时间:2013-06-30 01:52:46

标签: python recursion nodes avl-tree

我正在研究一个AVL树,除了删除一个节点方法之外我刚刚完成了。我现在有点卡住了,需要一些帮助。我这样做的方法是找到要删除的节点并以递归方式在路径中的每个节点上调用余额,以便在删除所需节点后,一系列树平衡将在树上完成其工作。不幸的是,由于一些奇怪的原因,平衡不能正常工作 - 我已经打印出来测试发生了什么,出于某种原因,如果我们有这样的树例如:

    6
   / \
 3      18 
  \    /  \
   5  9    74
          /  \
         50   99

并说我想删除9,所以会出现不平衡, 余额只会平衡6的根节点,而不是18 ......的节点。

def deleteNode(self, val, root, previous):

        if (val==root.value):

            if (root.right is None and root.left is None):
                if (previous is not None and (previous.value>root.value)):
                    previous.left=None
                else:
                    if (previous is not None and (previous.value<root.value)):
                        previous.right=None
                    else:
                        if (previous is None):
                            self.root=None
                return

            if (root.right is None and root.left is not None):

                if (previous is not None and (previous.value>root.value)):
                    previous.left=root.left
                else:
                    if (previous is not None and (previous.value<root.value)):
                        previous.right=root.left
                    else:
                        if (previous is None):
                            self.root=root.left
                return

            if (root.left is None and root.right is not None):

                if (previous is not None and (previous.value>root.value)):
                    previous.left=root.right
                else:
                    if (previous is not None and (previous.value<root.value)):
                        previous.right=root.right
                    else:
                        if (previous is None):
                            self.root=root.right
                return

            if (root.left is not None and root.right is not None):

                rval=self.maxValue(root.left).value
                self.deleteNode(self.maxValue(root.left).value , self.root, None)
                root.value=rval

                return






        else:
            if (root.value<val):
                self.deleteNode(val, root.right, root)


                if (root.right is not None):
                    print root.value,
                    print root.right.value
                    self.balance(root.right, root)
            else:
                if (root.value>val):
                    self.deleteNode(val, root.left, root)

                    if (root.left is not None):
                        print root.value,
                        print root.left.value

                        self.balance(root.left, root)

解决了 - 我的平衡系统不正确。

0 个答案:

没有答案