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
相关推荐
wangwangmoon_light11 分钟前
1.23 LeetCode总结(树)_一般树
算法·leetcode·职场和发展
不知名XL11 分钟前
day01 agent开发基础铺垫
python
-To be number.wan17 分钟前
Python爬取百度指数保姆级教程
爬虫·python
hnxaoli28 分钟前
win10小程序(十八)剪切板循环粘贴
python·小程序
wfbcg29 分钟前
每日算法练习:LeetCode 30. 串联所有单词的子串 ✅
算法·leetcode·职场和发展
APIshop30 分钟前
Java获取淘宝商品价格、图片与视频:淘宝开放平台API实战指南
开发语言·python
田梓燊39 分钟前
leetcode 48
算法·leetcode·职场和发展
6Hzlia43 分钟前
【Hot 100 刷题计划】 LeetCode 169. 多数元素 | C++ 哈希表基础解法
c++·leetcode·散列表
唐叔在学习1 小时前
Python移动端应用消息提醒开发实践
开发语言·python
好家伙VCC1 小时前
**发散创新:基于Python与OpenCV的视频流帧级分析实战**在当前人工智能与计算机视觉飞速发展的背景下
java·人工智能·python·计算机视觉