当前位置:网站首页>剑指 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)
边栏推荐
- error: C1083: 无法打开包括文件: “QString”: No such error: ‘QDir‘ file not found
- tidyverse based on data.table?
- Cesium 修改鼠标样式
- leetcode 2119. Numbers reversed twice
- 力扣707-设计链表——链表
- leetcode 326. 3 的幂
- 面试官:为什么 0.1 + 0.2 == 0.300000004?
- 简单又有效的基本折线图制作方法
- dataframe 多层索引 更换索引 df.swaplevel(axis=1)
- Leetcode 899. An orderly queue
猜你喜欢
【HiFlow】经常忘记签到怎么办?使用腾讯云场景连接器每天提醒你。
PyCharm function automatically add comments without parameters
From September 1st, my country has granted zero-tariff treatment to 98% of tax items from 16 countries including Togo
Cesium 修改鼠标样式
AWTK开发编译环境踩坑记录1(编译提示powershell.exe出错)
伪标签汇总
反射机制
模板字符串
Linux操作Jmeter(附带:关于连接上redis无法进行写入操作的问题),JMeter配置多用户进行压力测试
盲埋孔PCB叠孔设计的利与弊
随机推荐
chart.js多条曲线图插件
LeetCode_Digit Statistics_Medium_400. Nth Digit
leetcode 326. Powers of 3
小朋友学C语言(3):整数、浮点数、字符
461. 汉明距离
函数,递归以及dom简单操作
buildscript和allprojects的作用和区别是什么?
博士申请 | 美国明尼苏达大学葛畅教授招收隐私数据管理方向全奖博士/硕士/博后/访问学者...
通关剑指 Offer——剑指 Offer II 009. 乘积小于 K 的子数组
开源一夏 |如何优化线上服务器
leetcode 448. Find All Numbers Disappeared in an Array 找到所有数组中消失的数字(简单)
leetcode 1837. The sum of the digits in the K-base representation
字节跳动软件测试岗,前两面过了,第三面HR天坑,结局透心凉...
CheckBox列表项选中动画js特效
ES6 introduction and let, var, const
idea2021配置svn报错Cannot run program “svn“ (in directory “xxx“):CreateProcess error=2,系统找不到指定的文件
卷起来!阿里高工携 18 位高级架构师耗时 57 天整合的 1658 页面试总结
Markdown语法
How can a cloud server safely use local AD/LDAP?
LeetCode_位数统计_中等_400.第 N 位数字