Python已知后序遍历和中序遍历,求先序遍历

步骤一:树的构建

字典

python 复制代码
def createTree(arr1,arr2,tree):
    if len(arr1)==0 and len(arr2)==0 :return
    root = len(arr1)-1
    # print(arr1[root],root)
    flag = arr2.index(arr1[root])
    # print(flag)
    len_right = len(arr2)-flag-1
    len_left = flag
    if len(arr2[:flag])>=1:
        lchild = arr1[flag-1]
    else:
        lchild = None

    if len(arr2[flag+1:])>=1:
        rchild = arr1[root-1]
    else:
        rchild = None
    
    tree[arr1[root]] = {'lchild':None,'rchild':None}
    tree[arr1[root]]['lchild'] = lchild
    tree[arr1[root]]['rchild'] = rchild
    
    # print(tree)
    # print(arr1[:flag],arr1[len_left:len_left+len_right])
    # print(arr2[:flag],arr2[flag+1:])
    createTree(arr1[:flag],arr2[:flag],tree) # 左子树
    createTree(arr1[len_left:len_left+len_right],arr2[flag+1:],tree) #右子树

tree = dict()
back = [3,4,2,6,5,1]
mid = [3,2,4,1,6,5]
createTree(back,mid,tree)
复制代码
{1: {'lchild': 2, 'rchild': 5},
 2: {'lchild': 3, 'rchild': 4},
 3: {'lchild': None, 'rchild': None},
 4: {'lchild': None, 'rchild': None},
 5: {'lchild': 6, 'rchild': None},
 6: {'lchild': None, 'rchild': None}}

多级嵌套字典

python 复制代码
def set_nested_dict_value(d, keys, value):
    """
    根据键列表设置嵌套字典的值
    :param d: 原始字典
    :param keys: 键列表
    :param value: 要设置的值
    """
    # 从第一个键开始,逐层深入
    for key in keys[:-1]:
        # 如果当前键不存在,则创建一个空字典
        if key not in d:
            d[key] = {}
        # 下一层字典
        d = d[key]
    # 设置最后一个键的值
    d[keys[-1]] = value

def createTree(arr1,arr2,tree,step):
    print('------------------------------------------')
    # if len(arr1)==0 and len(arr2)==0 :
    #     print('结束')
    #     return

    root = len(arr1)-1
    print(arr1[root],root)

    flag = arr2.index(arr1[root])
    print(flag)

    len_right = len(arr2)-flag-1
    len_left = flag
    if len(arr2[:flag])>=1:
        lchild = arr1[flag-1]
    else:
        lchild = None

    if len(arr2[flag+1:])>=1:
        rchild = arr1[root-1]
    else:
        rchild = None
        
    tmp = dict()
    tmp['root'] = arr1[root]
    if tmp['root']!= None:
        tmp['lchild'] = {'root':lchild,'lchild':None,'rchild':None} if lchild != None else None
        tmp['rchild'] = {'root':rchild,'lchild':None,'rchild':None} if rchild != None else None
    print('tree',tree)
    print('step',step)

    if tree==dict():
        tree.update(tmp)
    else:
        set_nested_dict_value(tree, step, tmp)
    

    # print(tree)
    # print(arr1[:flag],arr1[len_left:len_left+len_right])
    # print(arr2[:flag],arr2[flag+1:])
    # if len(arr1[:flag])>0 and len(arr2[:flag])>0:
    #     createTree(arr1[:flag],arr2[:flag],tree,step+['lchild']) # 左子树
    # if len(arr1[len_left:len_left+len_right])>0 and len(arr2[flag+1:])>0:
    #     createTree(arr1[len_left:len_left+len_right],arr2[flag+1:],tree,step+['rchild']) #右子树
    # if len(arr1[:flag])==0 and len(arr2[:flag])==0 and len(arr1[len_left:len_left+len_right])==0 and len(arr2[flag+1:])==0:
    #     print('chu')
    #     print(tree)

    left_mid = arr2[:flag]
    right_mid = arr2[flag+1:]

    left_back = arr1[:flag]
    right_back = arr1[len_left:len_left+len_right]
    
    print(tree)
    print(left_back,right_back)
    print(left_mid,right_mid)
    if len(left_back)>0 and len(left_mid)>0:
        createTree(left_back,left_mid,tree,step+['lchild']) # 左子树
    if len(right_back)>0 and len(right_mid)>0:
        createTree(right_back,right_mid,tree,step+['rchild']) #右子树
    if len(left_back)==0 and len(left_mid)==0 and len(right_back)==0 and len(right_mid)==0:
        print('chu')
        print(tree)


tree = dict()

back = [3,4,2,6,5,1]
mid = [3,2,4,1,6,5]

createTree(back,mid,tree,[])
tree

简化

python 复制代码
def set_nested_dict_value(d, keys, value):
    """
    根据键列表设置嵌套字典的值
    :param d: 原始字典
    :param keys: 键列表
    :param value: 要设置的值
    """
    # 从第一个键开始,逐层深入
    for key in keys[:-1]:
        # 如果当前键不存在,则创建一个空字典
        if key not in d:
            d[key] = {}
        # 下一层字典
        d = d[key]
    # 设置最后一个键的值
    d[keys[-1]] = value

def createTree(arr1,arr2,tree,step):

    root = len(arr1)-1

    flag = arr2.index(arr1[root])

    len_right = len(arr2)-flag-1
    len_left = flag

    tmp = {'root':arr1[root],'lchild':None,'rchild':None} 

    if tree==dict():
        tree.update(tmp)
    else:
        set_nested_dict_value(tree, step, tmp)
    

    left_mid = arr2[:flag]
    right_mid = arr2[flag+1:]

    left_back = arr1[:flag]
    right_back = arr1[len_left:len_left+len_right]
    

    if len(left_back)>0 and len(left_mid)>0:
        createTree(left_back,left_mid,tree,step+['lchild']) # 左子树
    if len(right_back)>0 and len(right_mid)>0:
        createTree(right_back,right_mid,tree,step+['rchild']) #右子树


tree = dict()

back = [3,4,2,6,5,1]
mid = [3,2,4,1,6,5]

createTree(back,mid,tree,[])
tree
复制代码
{
	'root': 1,
	'lchild': {
		'root': 2,
		 'lchild': {'root': 3, 'lchild': None, 'rchild': None},
		 'rchild': {'root': 4, 'lchild': None, 'rchild': None}},
	'rchild': {
		'root': 5,
		'lchild': {'root': 6, 'lchild': None, 'rchild': None},
		'rchild': None}
  }

步骤二:先序遍历

python 复制代码
def preOrder(tree):
    
    print(tree['root'])
    if tree['lchild']:
        preOrder(tree['lchild'])
    if tree['rchild']:
        preOrder(tree['rchild'])
preOrder(tree)
复制代码
1
2
3
4
5
6
相关推荐
静听山水2 分钟前
Redis核心数据结构-ZSet
数据结构·redis
曲幽5 分钟前
FastAPI不止于API:手把手教你用Jinja2打造动态Web页面
python·fastapi·backend·jinja2·full stack·template engine·web development
禹凕10 分钟前
Python编程——进阶知识(多线程)
开发语言·爬虫·python
Ulyanov13 分钟前
基于Pymunk物理引擎的2D坦克对战游戏开发
python·游戏·pygame·pymunk
铉铉这波能秀14 分钟前
LeetCode Hot100数据结构背景知识之字典(Dictionary)Python2026新版
数据结构·python·算法·leetcode·字典·dictionary
程序媛徐师姐29 分钟前
Python基于爬虫的网络小说数据分析系统【附源码、文档说明】
爬虫·python·python爬虫·网络小说数据分析系统·pytho网络小说数据分析系统·python爬虫网络小说·python爬虫的网络小说数据
清水白石00836 分钟前
深入解析 LRU 缓存:从 `@lru_cache` 到手动实现的完整指南
java·python·spring·缓存
JaydenAI40 分钟前
[LangChain之链]LangChain的Chain——由Runnable构建的管道
python·langchain
kali-Myon41 分钟前
2025春秋杯网络安全联赛冬季赛-day3
python·安全·web安全·ai·php·web·ctf
Queenie_Charlie44 分钟前
stars(树状数组)
数据结构·c++·树状数组