重建二叉树及非递归遍历(py)

本文介绍了一种使用前序遍历和中序遍历序列重建二叉树的方法,并展示了先序、中序、后序及循环遍历的实现。通过递归和队列,实现了对二叉树节点的遍历和打印。

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

from queue import Queue

class solve:
    def __init__(self,val):
        self.val=val
        self.left=[]
        self.right=[]

def rebuild(first,me):
    if len(first)==1:
        root = solve(first[0])
        return root
    elif len(first)==0:
        return
    for i in range(len(me)):
        if me[i]==first[0]:
            ind=i
            break
    root =solve(first[0])
    root.left=rebuild(first[1:ind+1],me[0:ind])
    root.right=rebuild(first[ind+1:],me[ind+1:])
    return root

def travel_first(root):
    if root:#递归记得写出口条件
        print(root.val,end='')
        travel_first(root.left)
        travel_first(root.right)

def travel_me(root):
    if root:#递归记得写出口条件
        travel_me(root.left)
        print(root.val,end='')
        travel_me(root.right)

def travel_last(root):
    if root:#递归记得写出口条件
        travel_last(root.left)
        travel_last(root.right)
        print(root.val,end='')

def travel_cycle(root):#若孩子存在,则压入队列
    que=Queue()
    que.put(root)
    while True:
        if que.empty():  #empty后面要加()
            break
        root = que.get()
        print(root.val,end='')
        if root.left:
            que.put(root.left)
        if root.right:
            que.put(root.right)


first='12473568'
me='47215386'
root=rebuild(first,me)
print('先序遍历')
travel_first(root)
print()
print('中序遍历')
travel_me(root)
print()
print('后序遍历')
travel_last(root)
print()
print('循环遍历')
travel_cycle(root)

结果为:

先序遍历
12473568
中序遍历
47215386
后序遍历
74258631
循环遍历
12345678
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值