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
相关推荐
暗黑小白15 分钟前
路由策略与引擎可替换性
后端·python·ai agent
小罗水29 分钟前
第 20 章 高级 RAG 技术与检索优化
人工智能·python·机器学习
bamb001 小时前
一个项目带你入门AI应用开发06
python
liwulin05061 小时前
【ESP32S3】调用百度云语音合成接口后重启
python
程序员-珍1 小时前
力扣 877. 石子游戏
算法·leetcode·游戏
m沐沐1 小时前
【机器学习】矿物识别系统实战——六种填充方法×六种模型全面对比
人工智能·python·深度学习·机器学习·矿物识别
软糖姐姐1 小时前
Python:__closure__ 详解
python·闭包·__closure__·自由变量·cell对象
月光船幽幽1 小时前
四层公理框架驱动AI健康诊断
人工智能·python·科技·算法·安全
Rabitebla2 小时前
C++ STL 之 set 详解:从底层红黑树到实际应用
开发语言·数据结构·c++·算法·leetcode
郝学胜-神的一滴2 小时前
力扣 692:巧用小顶堆高效求解前K个高频单词
java·数据结构·python·程序人生·算法·leetcode·职场和发展