删除二叉树中的最小元素

时间:2015-12-12 17:55:23

标签: python algorithm tree binary-tree min

如何删除二叉树中的最小元素?我知道当他们要求你删除某个元素时如何删除,但我真的很难过这个。以下是删除树中特定值的代码。

def delete(tree):
    if tree == None:
        return None
    else:
        if tree['left']['left'] == None:
            tree['left'] = None
         #this is where I get stuck

2 个答案:

答案 0 :(得分:0)

我建议使用the heapq implementation provided in the Python standard library直接完成从二叉树中删除最小值的任务,然后研究the source code of the heapq module以了解算法的实现方式。

import heapq
from random import seed, randint

seed(0)
items = [randint(1,100) for i in range(10)]
# [85, 76, 43, 26, 52, 41, 79, 31, 48, 59]

# create the heap queue / priority queue
h = []
for i in items:
    heapq.heappush(h, i)

# the smallest item
heapq.heappop(h)
# 26

答案 1 :(得分:0)

在我看来,你只是忘了包含递归步骤。我已将其包含在下面的代码中。

def delete(tree):
    if tree == None:
        return None
    else:
        if tree['left']['left'] == None:
            tree['left'] = tree['left']['right'] # I also changed this
        else:
            delete(tree['left']) # recursive part

如果tree['left']['left'] != None您知道最小值位于树左侧的某个位置,那么只需在该侧再次调用delete(),直到找到{{1}的节点为止}。