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
相关推荐
天才少女爱迪生11 小时前
word格式规范检测+自动修改【python】
python·c#·word
南宫萧幕11 小时前
基于 PSO 的 HEV 能量管理策略:从联合仿真建模到排错实战
开发语言·python·算法·matlab·控制
在下_诸葛11 小时前
langgraph学习笔记
笔记·python·学习·langgraph教程
Muyuan199811 小时前
26.Paper RAG Agent 展示面收口:截图与项目表达更新记录
人工智能·python·django·fastapi
AI技术增长11 小时前
Pytorch图像去噪实战(十四):条件扩散模型图像去噪,让Diffusion根据带噪图恢复干净图
人工智能·pytorch·python
li星野11 小时前
FastAPI 项目加入 WebSocket 支持
python·websocket·fastapi
tangweiguo0305198712 小时前
LangGraph 入门:多智能体工作流实战(阿里云百炼)
人工智能·python·langchain
Ares-Wang12 小时前
Flask》》Flask-Caching缓存插件
python·缓存·flask
明如正午12 小时前
转换pdf文件为md文件【markitdown+pdf4llm】
python·pdf·markitdown·pdf4llm
咯哦哦哦哦12 小时前
Foundationpose环境配置【非conda--纯UV】(linux22.04+python3.10)
python·pip·uv