力扣:105. 从前序与中序遍历序列构造二叉树(Python3)

题目:

给定两个整数数组 preorderinorder ,其中 preorder 是二叉树的先序遍历inorder 是同一棵树的中序遍历,请构造二叉树并返回其根节点。

来源:力扣(LeetCode)

链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

示例:

示例 1:

输入:preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]

输出:[3,9,20,null,null,15,7]

示例 2:

输入:preorder = [-1], inorder = [-1]

输出:[-1]

解法:

使用栈辅助(stack),栈中每个结点结构为[当前结点在中序序列中的下标, 树节点],stack初始化的值是前序序列第0个。用栈的目的是当插入结点为右子树时确定其根节点。

遍历前序序列, 从第1个开始。获取当前值在中序序列中的下标,如果比stack中最后1个小,说明当前结点是前个结点的左子树;否则需要弹出栈顶,直到比stack中最后1个大,此时说明当前结点在弹出结点的右边,在栈最后1个结点的左边,所以把当前结点接到弹出结点的右子树。

知识点:

**1.前序遍历:**根-左-右。

代码:

python 复制代码
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
        root = tree = TreeNode(preorder[0])
        stack = [[inorder.index(preorder[0]), tree]]
        for num in preorder[1:]:
            index = inorder.index(num)
            tree = TreeNode(num)
            if index < stack[-1][0]:
                stack[-1][1].left = tree
            else:
                while stack and index > stack[-1][0]:
                    pre = stack.pop()
                pre[1].right = tree
            stack.append([index, tree])
        return root
相关推荐
程序设计实验室12 小时前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三14 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
用户25191624271117 小时前
Python之语言特点
python
刘立军17 小时前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
聚客AI19 小时前
🙋‍♀️Transformer训练与推理全流程:从输入处理到输出生成
人工智能·算法·llm
数据智能老司机21 小时前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
大怪v21 小时前
前端:人工智能?我也会啊!来个花活,😎😎😎“自动驾驶”整起!
前端·javascript·算法
数据智能老司机1 天前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i1 天前
django中的FBV 和 CBV
python·django
c8i1 天前
python中的闭包和装饰器
python