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

Prolog中带leafs属性的tree(Node,Leafs)结构二叉树节点计数咨询

自定义tree(Node, Leafs)结构的节点计数实现方案

该结构无传统二叉树的左右分支强制区分,所有关联子节点统一存放在Leafs数组中,无论单节点下的子节点数量多少,计数逻辑都不需要做分支方向判断。

递归实现(逻辑简洁适配常规场景)

核心逻辑为:每个树实例的总节点数 = 当前节点本身(计1) + 所有子树的节点数累加和;当Leafs为空时,直接返回1作为递归终止条件。
示例代码:

def count_nodes(root_tree):
    node_count = 1
    for child in root_tree.Leafs:
        node_count += count_nodes(child)
    return node_count

示例计算验证

拿给出的结构tree(node4, [tree(node6, [tree(node2, [])])])计算,结果应为3:

  • 最内层tree(node2, []):无叶子子节点,返回1
  • 中间层tree(node6, [tree(node2, [])]):1 + 内层节点数1 = 2
  • 最外层tree(node4, [tree(node6, [tree(node2, [])])]):1 + 中间层节点数2 = 3

迭代实现(适配深层树避免递归栈溢出)

如果树的层级过深,递归可能触发调用栈溢出,可使用栈实现深度优先遍历的迭代计数:

def count_nodes_iterative(root_tree):
    total = 0
    stack = [root_tree]
    while stack:
        current_node = stack.pop()
        total +=1
        # 所有子树直接压入栈,顺序不影响最终计数结果
        stack.extend(current_node.Leafs)
    return total

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.22 17:06:02