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
相关推荐
Dxy12393102168 分钟前
Python 实现POST上行压缩上传可用HTTP库汇总
开发语言·python·http
荣码13 分钟前
AI应用部署上线:Docker打包+API服务+监控告警,我踩了4个坑
java·python
郝学胜-神的一滴19 分钟前
Python 高级编程 026:序列内核深剖
开发语言·python·程序人生·软件工程
神奇霸王龙20 分钟前
Qwen3.7-Max屠榜:推理成本仅GPT-5.5的1/25
人工智能·python·gpt·ai·aigc·ai编程
玖玥拾21 分钟前
LeetCode 80 删除有序数组中的重复项 II
算法·leetcode
渣男教父24 分钟前
Python-openpyxl操作Excel
python
青山木34 分钟前
Hot 100 --- 电话号码的字母组合
java·数据结构·算法·leetcode·逻辑回归
hanlin0344 分钟前
刷题笔记:力扣第206题-反转链表
笔记·leetcode·链表
华研前沿标杆游学1 小时前
2026标杆游学落地实践:某科技企业半年效率提升30%的实操
python
zh路西法1 小时前
【双目相机 深度估计】PixelXYZ 3D 双目相机标定与实时深度估计全流程
python·opencv·相机标定·深度估计·双目相机·sgbm