删除二叉搜索树中的节点

时间:2020-11-04 12:39:29

标签: python binary-search-tree

我有一个由[21,9,4,2,2,3,7,14,14,10,18,15,26,30,28,]组成的二叉搜索树。我正在尝试从树中删除元素,但是每当尝试删除26时,我都会得到

    21, 9, 4, 2, 3, 7, 14, 10, 18, 15, 26, 30, 28,
    Greater than current node 21
    Found 26
    New cursor 30

    21, 9, 4, 2, 3, 7, 14, 10, 18, 15, 26, 30, 28,

我认为问题可能与我使用= None有关,但找不到问题,因为它说它用30代替了Node

    *print statement*

def remove_helper(self, cursor, data):
    
    if (cursor == None):
        return

    if cursor.data > data:
        print("Less than current node " + str(cursor.data))
        if cursor.left_child is None:
            return
        else:
            self.remove_helper(cursor.left_child, data)

    elif cursor.data < data:
        print("Greater than current node" + str(cursor.data))
        if cursor.right_child is None:
            return
        else:
            self.remove_helper(cursor.right_child, data)

    else:
        print("Equals " + str(cursor.data))
        if cursor.left_child is None and cursor.right_child is None:
            print("No children")
            cursor = None
            return cursor
        if cursor.left_child is None:
            cursor = cursor.right_child
            print("New cursor " + str(cursor.data))

            return cursor
        elif cursor.right_child is None:
            cursor = cursor.left_child
            print("New cursor " + str(cursor.data))
            return cursor

    *Same print statement*

0 个答案:

没有答案