力扣: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
相关推荐
To_OC10 小时前
LC 207 课程表:刚学图论那会儿,我连这是拓扑排序都没看出来
javascript·算法·leetcode
To_OC10 小时前
LC 208 实现 Trie 前缀树:曾被名字劝退,写完发现是送分题
javascript·算法·leetcode
BadBadBad__AK12 小时前
线段树维护区间 k 次方和
c++·数学·算法·stl
Warson_L17 小时前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅17 小时前
海天线算法的前世今生
python·计算机视觉
韩师傅17 小时前
当你的甲方设备过烂,要如何快速出效果?
python·计算机视觉
Warson_L17 小时前
LangGraph的MessageState and HumanMessage
python
韩师傅18 小时前
当你的甲方吐槽天空不够蓝,你应该如何应对
python·计算机视觉
Warson_L18 小时前
python的类&继承
python
Warson_L18 小时前
类型标注/type annotation
python