一种非递归解决多叉树深度访问的方法

该博客内容涉及树形结构的数据组织,重点介绍了如何通过深度优先搜索(DFS)遍历一棵以字符表示的树。代码实现了一个简单的树结构,并提供了从根节点开始的DFS遍历方法,输出了节点的顺序。该方法适用于递归遍历具有层级关系的数据结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 问题描述:

'''
例如:
A  A1  A11
    A2  A21  A211  A2111
                             A2112
                   A212  A2121
          A22
    A3  A31   A311
          A32   A321 A322
  A4
  
期望的输出:A A1 A11 A2 A21 A211 A2111 A2112 A212 A2121 A22 A3 A31 A311 A32 A321 A322
'''

其中,A1是A的子节点,A11是A1的子节点,A2是A的第二子节点,A21是A2的第一子节点

import re


class A:
    def __init__(self, name):
        self.name = name
        self.child = []
        self.parent = None
        self.is_visit = False
        self.child_visit_position = -1

    def add_child(self, node):
        self.child.append(node)

    def set_parent(self, node):
        self.parent.append(node)

    def visit(self):
        self.is_visit = True




def build_tree():

    tree_str = '''
    A A1 A11
      A2 A21 A211 A2111
                  A2112
             A212 A2121
         A22
      A3 A31 A311
         A32 A321 A322
      A4'''
    result = list(filter(lambda x: x.strip(), re.split(r'[\n\r ]', tree_str)))

    node_map = {each: A(each) for each in result}

    for each in result:
        node = node_map.get(each)
        node_name = node.name
        if len(node_name) == 1:
            continue
        else:
            parent_name = node_name[:-1]
            parent_node = node_map.get(parent_name)
            node.parent = parent_node
            parent_node.child.append(node)
    return node_map.get("A")


def visit_tree(root_tree: A):
    visit_list = []
    current_root = root_tree
    while True:
        if not current_root.is_visit:
            visit_list.append(current_root.name)



            current_root.is_visit=True

        if len(current_root.child)>0:
            if current_root.child_visit_position < len(current_root.child)-1:
                current_root.child_visit_position +=1
                current_root = current_root.child[current_root.child_visit_position]
                continue

        if current_root.parent is not None:
            current_root = current_root.parent
            continue
        if current_root.parent is None and (len(current_root.child)<=0 or  current_root.child_visit_position >=len(current_root.child)-1):
            break
    print("\n".join(visit_list))


root_node = build_tree()

visit_tree(root_node)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

会发paper的学渣

您的鼓励和将是我前进的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值