Python | Leetcode Python题解之第105题从前序与中序遍历序列构造二叉树

题目:

题解:

python 复制代码
class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
        if not preorder:
            return None

        root = TreeNode(preorder[0])
        stack = [root]
        inorderIndex = 0
        for i in range(1, len(preorder)):
            preorderVal = preorder[i]
            node = stack[-1]
            if node.val != inorder[inorderIndex]:
                node.left = TreeNode(preorderVal)
                stack.append(node.left)
            else:
                while stack and stack[-1].val == inorder[inorderIndex]:
                    node = stack.pop()
                    inorderIndex += 1
                node.right = TreeNode(preorderVal)
                stack.append(node.right)

        return root
相关推荐
copyer_xyf6 分钟前
Python 类全面总结
前端·后端·python
copyer_xyf10 分钟前
Python 类型注解:从 TypeScript 迁移理解
前端·后端·python
8Qi811 分钟前
LeetCode 474:一和零(Ones and Zeroes)—— 题解 ✅
算法·leetcode·职场和发展·动态规划·01背包
276695829211 分钟前
谷歌google cookie逆向角度分析
开发语言·python·google·sgss·谷歌搜索·sg-ss·谷歌cookie逆向
copyer_xyf17 分钟前
Python 函数全面总结
前端·后端·python
zmzb010318 分钟前
Python课后习题训练记录Day123
开发语言·python
PersistJiao20 分钟前
python环境下免费、专业的中英翻译
开发语言·windows·python·机器翻译
hujinyuan2016035 分钟前
中国电子学会青少年软件编程(Python)(二级)等级考试试卷-真题+答案(2026年3月)
python·机器人
Lsk_Smion37 分钟前
力扣实训 _ [98].验证二叉搜索树 _ 将二叉树展开成链表
数据结构·算法·leetcode