如何编写可以接受二叉树作为参数的函数,如果它是最小堆,则返回True,如果不是,则返回False.

from heapq import heapify

def binary_heap(tree):
  while len(tree) > 1:
    if heapify(tree):
        return True
    else:
        return False

推荐答案

由于最小堆必须满足每heapq‘S documentation:

heap[k] <= heap[2*k+1] and heap[k] <= heap[2*k+2]

您可以遍历所有子 node 以验证它们是否大于或等于其父 node (请注意,i - 1 >> 1(i - 1) // 2 When i > 0的缩写):

def is_minheap(lst):
    return all(lst[i] >= lst[i - 1 >> 1] for i in range(1, len(lst)))

因此:

from heapq import heapify
from random import sample

lst = sample(range(10), 10)
print(is_minheap(lst), lst)
heapify(lst)
print(is_minheap(lst), lst)

输出内容类似于:

False [1, 2, 6, 8, 0, 5, 3, 9, 7, 4]
True [0, 1, 3, 7, 2, 5, 6, 9, 8, 4]

演示:https://ideone.com/1uhd6c

Python相关问答推荐

为什么Pydantic在我申报邮箱时说邮箱丢失

两极按组颠倒顺序

有没有办法清除气流中的僵尸

如何将不同长度的新列添加到现有的框架中

获取Azure Pipelines以从pyproject.toml(而不是relevments_dev.文本)安装测试环境

更改Seaborn条形图中的x轴日期时间限制

计算所有前面行(当前行)中列的值

Class_weight参数不影响RandomForestClassifier不平衡数据集中的结果

如何从具有多个嵌入选项卡的网页中Web抓取td类元素

使用mySQL的SQlalchemy过滤重叠时间段

try 在树叶 map 上应用覆盖磁贴

ModuleNotFound错误:没有名为flags.State的模块; flags不是包

输出中带有南的亚麻神经网络

数据抓取失败:寻求帮助

无法使用requests或Selenium抓取一个href链接

对象的`__call__`方法的setattr在Python中不起作用'

Odoo 16使用NTFS使字段只读

实现神经网络代码时的TypeError

如何使用Numpy. stracards重新编写滚动和?

matplotlib图中的复杂箭头形状