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
相关推荐
进击的小白菜22 分钟前
如何高效实现「LeetCode25. K 个一组翻转链表」?Java 详细解决方案
java·数据结构·leetcode·链表
拾忆-eleven35 分钟前
C++算法(19):整数类型极值,从INT_MIN原理到跨平台开发实战
数据结构·c++·算法
985小水博一枚呀1 小时前
【EI会议推荐】2025年6月智启未来:通信导航、 机器学习、半导体与AI、数字创新领域国际研讨会总结!
人工智能·python·深度学习·机器学习
www_pp_2 小时前
# 创建一个功能完备的计算器应用:使用PyQt5和Python
开发语言·python·qt
攻城狮7号2 小时前
大模型微调Fine-tuning:从概念到实践的全面解析
人工智能·python·前沿技术·fine-tuning·大模型微调
basketball6162 小时前
使用pytorch保存和加载预训练的模型方法
人工智能·pytorch·python
我是一只鱼02232 小时前
LeetCode算法题 (反转链表)Day17!!!C/C++
数据结构·c++·算法·leetcode·链表
蓑笠翁0012 小时前
Python异步编程入门:从同步到异步的思维转变
linux·前端·python
程序员Bears3 小时前
Django进阶:用户认证、REST API与Celery异步任务全解析
后端·python·django
仰望星空的凡人3 小时前
【JS逆向基础】前端基础-HTML与CSS
css·python·html·js逆向