删除无法在python中运行的二叉搜索树的函数

时间:2017-12-11 07:35:23

标签: python-3.x data-structures binary-search-tree

class Node:
    def __init__(self,value = None):
        self.value = value
        self.left = None
        self.right = None

class BinarySearchTree:
    def __init__(self):
        self.root = None

    def insert(self,value):
        if self.root != None:
            self._insert(self.root,value)
        else:
            self.root = Node(value)

    def _insert(self,current,value):
        if value < current.value:
            if current.left == None:
                current.left = Node(value)
            else:
                self._insert(current.left,value)

        elif value > current.value: 
            if current.right == None:
                current.right = Node(value)
            else:   
                self._insert(current.right,value)
        else:
            print("Value already exist in tree.")


    def delete(self,current,value):
        if current == None: return current
        elif value < current.value: current.left = self.delete(current.left,value)
        elif value > current.value: current.right = self.delete(current.right,value)
        else:
            if current.left == None and current.right == None:
                current = None # case 0
            elif current.left == None: return current.right # case 1r
            elif current.right == None: return current.left # case 1l
            else:  # case 2
                temp = self.min(current.right)
                current.value = temp
                self.delete(current.right,temp)
        return current

    def min(self,current): 
        if current != None:
            return self._min(current)
        else:
            return None

    def _min(self,current):
        if current.left != None:
            return self._min(current.left)
        else:
            return current.value

if __name__ == '__main__':
    for i in (12,5,18,3,4,6):
        tree.insert(i)
    tree.delete(tree.root,12)

大家好,我的二分查找树的删除功能不适用于有2个孩子的节点,并希望得到一些帮助。

问题是由删除功能的第6行和第12行引起的,其中行self.delete(current.right,temp)指向current = None # case 0current = None # case 0行不会将当前值更改为0,我对此非常困惑。知道什么是错的吗?

1 个答案:

答案 0 :(得分:1)

将delete方法中的第12行替换为:

current.right = self.delete(current.right, temp)

原因很简单:current = None只影响本地值,不会影响节点12的左子或右子。