You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

B树节点统计问题:无法正确遍历多层B树统计含n个元素的节点

B树遍历问题:找出含指定元素数的所有节点

给定一棵多层B树,需要找出所有包含n个元素的节点,但原遍历代码无法正确递归访问下层节点,导致统计结果不全。

原错误代码

def nodes_with_n_items(T,n):
    L = []
    if len(T.data) == n:
        L.append(T)
    if len(T.child) == 0:
        return L
    
    for item in T.child:
        if len(item.data) == n:
            L.append(item)
        L + nodes_with_n_items(item, n)

    return L

问题分析

  1. 手动判断子节点元素数并添加属于冗余操作,递归逻辑本身会处理所有节点的判断
  2. 核心错误:L + nodes_with_n_items(item, n)仅生成新列表,但未将结果合并到原列表L中,导致递归返回的下层节点数据丢失

修改后的正确代码

def nodes_with_n_items(T,n):
    L = []
    # 检查当前节点是否符合条件
    if len(T.data) == n:
        L.append(T)
    # 遍历所有子节点,递归收集符合条件的节点
    for child_node in T.child:
        # 将递归返回的结果合并到当前列表
        L.extend(nodes_with_n_items(child_node, n))
    return L

修改说明

  • 移除对子节点的手动判断,让递归统一处理所有层级的节点(当前节点+所有子节点)
  • 使用L.extend(...)替代L + ...,将递归得到的子节点列表直接合并到主列表,确保所有符合条件的节点都被收集

验证结果

修改后运行主函数,将得到预期输出:

There are 1 nodes with 1 items
[11]
There are 4 nodes with 2 items
[2, 6]
[0, 1]
[12, 13]
[15, 16]
There are 3 nodes with 3 items
[3, 4, 5]
[14, 17, 21]
[18, 19, 20]
There are 2 nodes with 4 items
[7, 8, 9, 10]
[22, 23, 24, 25]
There are 0 nodes with 5 items

内容的提问来源于stack exchange,提问作者hii

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 11:57:45