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

如何通过递归实现n叉树多层节点访问与子节点添加?

递归实现表达式到N叉树的转换问题

我需要将不同长度、复杂度的表达式插入到自定义的**N叉树(NonBinTree)**中,表达式示例如下:

invalid_expr = ["(", "SOME", "&", "THING", ")", "|", "INVALID", "&", "(", "GOES", "|", "IN", "|", "HERE", ")"]
simple_expr = ["VERY", "&", "SIMPLE", "&", "EXPRESSION", "&", "(", "NO", "|", "BIG", "|", "DEAL", ")"]
complicated_expr = ["(", "MORE", "&", "(", "COMPLICATED", "|","(","EXPRESSION","&","PRESENTING",")","|", "MANY", ")", ")", "|", "(", "DEEPER", "&", "(", "LEVELS", "|", "FOR", "|", "TREE", ")",")"]

N叉树的类定义如下:

class NonBinTree:

    def __init__(self, val):
        self.val = val
        self.nodes = []

    def add_node(self, val):
        self.nodes.append(NonBinTree(val))
    
    def add_child_node(self, parent, val):
        self.nodes[parent].add_node(val)

    def make_parent_node(self, parent, val):
        self.nodes[parent] = NonBinTree(val)

    
    def __repr__(self):
        return f"NonBinTree({self.val}): {self.nodes}"

当前的处理逻辑是:将括号内的内容作为列表节点,括号外的单个字符串作为节点;公共运算符作为父节点,非运算符字符串或列表作为子节点。现有处理代码如下:

pre_inserted_nodes, operator = create_nodes(an_expr)
a = NonBinTree(list(operator)[0])
for i in pre_inserted_nodes:
    if i != list(operator)[0]:
        a.add_node(i)
i=0
while i < len(pre_inserted_nodes):
    if isinstance(pre_inserted_nodes[i], list):
        pre_inserted_nodes[i].pop(0)
        pre_inserted_nodes[i].pop()
        new_pre_inserted_nodes, new_operator = create_nodes(pre_inserted_nodes[i])
        temp_new_pre_inserted_nodes = copy.deepcopy(new_pre_inserted_nodes)
        for node_index in range(len(temp_new_pre_inserted_nodes)):
            if not isinstance(temp_new_pre_inserted_nodes[node_index], list):
                if temp_new_pre_inserted_nodes[node_index] == list(new_operator)[0]:
                    new_pre_inserted_nodes.pop(node_index)
        a.make_parent_node(i, list(new_operator)[0])
        for node in new_pre_inserted_nodes:
            a.add_child_node(i, node)
    i += 1

但当表达式嵌套深度达到5层时,现有迭代逻辑无法处理动态多层节点的访问与子节点添加(比如需要访问a.nodes[0].nodes[0].nodes[1].nodes[1]并调用add_node),求如何通过递归实现该逻辑,支持动态添加.nodes[x]层级的节点访问与操作。

内容的提问来源于stack exchange,提问作者Meike Magdalena Büttner

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 01:15:01