当前位置:网站首页>剑指 Offer 07. 重建二叉树
剑指 Offer 07. 重建二叉树
2022-08-03 21:00:00 【愈努力俞幸运】
剑指 Offer 07. 重建二叉树
https://leetcode.cn/problems/zhong-jian-er-cha-shu-lcof/
首先,基本的知识点要了解,可参考下面这篇文章
剑指 Offer 07. 重建二叉树
https://leetcode.cn/problems/zhong-jian-er-cha-shu-lcof/
根据以上性质,可得出以下推论:
前序遍历的首元素 为 树的根节点 node 的值。
在中序遍历中搜索根节点 node 的索引 ,可将 中序遍历 划分为 [ 左子树 | 根节点 | 右子树 ] 。
根据中序遍历中的左(右)子树的节点数量,可将 前序遍历 划分为 [ 根节点 | 左子树 | 右子树 ] 。
通过以上三步,可确定 三个节点 :1.树的根节点、2.左子树根节点、3.右子树根节点。
对于树的左、右子树,仍可复用以上方法划分子树的左右子树。

class Solution:
def buildTree(self, preorder, inorder):
def recur(root,left,right):
if left>right:return
node=TreeNode(preorder[root])
i = dic[node.val]
node.left=recur(root+1,left,i-1)
node.right=recur(root+i-left+1,i+1,right)
return node
dic={}
for i in range(len(inorder)):
dic[inorder[i]]=i
return recur(0,0,len(inorder)-1)
边栏推荐
- 基于DMS的数仓智能运维服务,知多少?
- leetcode 16.01. Swap numbers (swap the values of 2 numbers without using temporary variables)
- 云服务器如何安全使用本地的AD/LDAP?
- LeetCode_位数统计_中等_400.第 N 位数字
- leetcode 326. Powers of 3
- 3种圆形按钮悬浮和点击事件
- leetcode 16.01. 交换数字(不使用临时变量交换2个数的值)
- ECCV 2022 | 清华&腾讯AI Lab提出REALY:重新思考3D人脸重建的评估方法
- Likou 59 - Spiral Matrix II - Boundary Judgment
- Lecture topics and guest blockbuster, TDengine developers conference to promote data technology "broken"
猜你喜欢

从开发到软件测试:除了扎实的测试基础,还有哪些必须掌握 ?

【使用 Pytorch 实现入门级的人工神经网络】

业界新标杆!阿里开源自研高并发编程核心笔记(2022 最新版)

From September 1st, my country has granted zero-tariff treatment to 98% of tax items from 16 countries including Togo

461. 汉明距离

Transformer怎么入门?如何学习Transformer?

PyCharm函数自动添加注释无参数问题

15年软件架构师经验总结:在ML领域,初学者踩过的五个坑

canvas螺旋动画js特效

火了十几年的零信任,为啥还不能落地
随机推荐
力扣203-移除链表元素——链表
《QDebug 2022年7月》
From September 1st, my country has granted zero-tariff treatment to 98% of tax items from 16 countries including Togo
Engineering Effectiveness Governance for Agile Delivery
Transformer怎么入门?如何学习Transformer?
在树莓派上搭建属于自己的网页(3)
Zero trust, which has been popular for more than ten years, why can't it be implemented?
Markdown syntax
461. 汉明距离
有趣的opencv-记录图片二值化和相似度实现
LeetCode_Digit Statistics_Medium_400. Nth Digit
好朋友离职了,一周面试了20多场,我直呼内行
华为设备配置VRRP负载分担
Leetcode sword refers to Offer 15. 1 in the binary number
leetcode 16.01. Swap numbers (swap the values of 2 numbers without using temporary variables)
How can a cloud server safely use local AD/LDAP?
chart.js多条曲线图插件
不专业面试官的经验总结
为什么 BI 软件都搞不定关联分析
直播源码开发,各种常见的广告形式