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
相关推荐
To_OC4 小时前
LC 207 课程表:刚学图论那会儿,我连这是拓扑排序都没看出来
javascript·算法·leetcode
To_OC4 小时前
LC 208 实现 Trie 前缀树:曾被名字劝退,写完发现是送分题
javascript·算法·leetcode
Warson_L11 小时前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅11 小时前
海天线算法的前世今生
python·计算机视觉
韩师傅11 小时前
当你的甲方设备过烂,要如何快速出效果?
python·计算机视觉
Warson_L11 小时前
LangGraph的MessageState and HumanMessage
python
韩师傅12 小时前
当你的甲方吐槽天空不够蓝,你应该如何应对
python·计算机视觉
Warson_L12 小时前
python的类&继承
python
Warson_L12 小时前
类型标注/type annotation
python
ThreeS14 小时前
手搓MiniVLA全实战教程-一步一步用pytorch解释原理与思路
人工智能·python