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
相关推荐
BD_Marathon1 小时前
安装Jupyter notebook
ide·python·jupyter
Zlzxzw2 小时前
End-to-End Autonomous Generation of Human Assembly Plans
python
Wellijohn2 小时前
2000 个请求、30% 失败率:我把 Python 批量并发的限流和重试参数算了一遍
后端·python·性能优化
Logintern094 小时前
deep agents 多智能体模式——规划与委派
python·langchain
2601_967980116 小时前
Python 办公自动化合集 ⑰:Excel自动计算——总和/平均分/最大值
python·pycharm·办公自动化·数据处理·excel自动计算
databook8 小时前
时间序列预测,模型换了一圈为什么没变好
python·数据分析
reasonsummer8 小时前
【教学类-07-17】20261119大3班破译电话号码HTML实际操作(添加“跳过按钮”和“返回按钮”在底部、增加“自编题目+解题”部分)
python·html
wy_hhxx8 小时前
[Leetcode] 滑动窗口
算法·leetcode·滑动窗口
AIgorithmGEEK10 小时前
算法·哈希表|从“逐个比”到“按 key 算位置”
数据结构·c++·算法·leetcode·hash
2601_9679801112 小时前
Python闭包(Closure)详解
python·作用域·装饰器·函数式编程·闭包