当前位置:网站首页>重建二叉树
重建二叉树
2022-07-30 00:09:00 【龙崎流河】
题目:
输入某二叉树的前序遍历和中序遍历的结果,请构建该二叉树并返回其根节点。
假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
示例一:
Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]
分析:
找到递归关系
代码:
import java.util.HashMap;
import java.util.Map;
public class BuildTree {
// 利用哈希函数方便得到下标
Map<Integer, Integer> map = new HashMap<>();
public TreeNode buildTree(int[] preorder, int[] inorder) {
if (preorder == null || preorder.length == 0){
return null;
}
for (int i = 0; i < inorder.length; i++) {
map.put(inorder[i],i);
}
TreeNode root = f(preorder,0,preorder.length-1,inorder,0,inorder.length-1);
return root;
}
private TreeNode f(int[] preorder, int l1, int r1, int[] inorder, int l2, int r2) {
if (l1 > r1 || l2 > r2){
return null;
}
TreeNode root = new TreeNode(preorder[l1]);
//得到根节点下标
int i = map.get(preorder[l1]);
root.left = f(preorder,l1+1,l1+i-l2,inorder,l2,i-1);
root.right = f(preorder,l1+i-l2+1,r1,inorder,i+1,r2);
return root;
}
}

边栏推荐
- I.MX6U-驱动开发-3-新字符驱动
- Expansion of Parallel I/O Port in Single Chip Microcomputer Development
- 4 hotspot inquiry networks necessary for new media operations
- YoloV5数据集自动划分训练集、验证集、测试集
- Codeforces Round #805 (Div. 3)总结
- Go日志库——logrus
- EA&UML日拱一卒-多任务编程超入门-(8)多任务安全的数据类
- How do we-media people create explosive articles?These 3 types of articles are most likely to explode
- 第一范式、第二范式、第三范式
- rk-boot框架实战(1)
猜你喜欢

经典论文-SqueezeNet论文及实践

关于MySQL索引的一些个人理解(部分参考MySQL45讲)

Paper Intensive Reading - YOLOv3: An Incremental Improvement

基于TNEWS‘ 今日头条中文新闻(短文本)分类

SQL Server、MySQL主从搭建,EF Core读写分离代码实现

EA & UML Sun Gong Yip - Multitasking Programming Super Introductory - (7) About mutex, you must know

KDE Frameworks 5.20.0:Plasma迎来诸多改进

关于 byte 的范围

Worthington Dissociation Enzymes: Trypsin and Frequently Asked Questions

UE4 makes crosshair + recoil
随机推荐
决策树原理及代码实现
对数据库进行增删改查操作
ZLMediaKit源码分析 - NotifyCenter
Reading notes. This is the psychology: see through the essence of the pseudo psychology (version 10)"
Go日志库——logrus
The go language (functions, closures, defer, panic/recover, recursion, structure, json serialization and deserialization)
Worthington Dissociation Enzymes: Trypsin and Frequently Asked Questions
微信开发者工具设置制表符大小为2
NumPy(一)
随便记记第二周
kubernets学习 -环境搭建
定时器学习
CesiumJS 2022^ 源码解读[0] - 文章目录与源码工程结构
One article to answer web performance optimization
4 hotspot inquiry networks necessary for new media operations
BEVDetNet: Bird's Eye View LiDAR Point Cloud based Real-time 3D Object Detection for Autonomous Drivi
2022/7/29 考试总结
利用热点事件来创作软文的3大技巧?自媒体人必看
Go language serialization and deserialization and how to change the uppercase of the json key value to lowercase if the json after serialization is empty
Adaptive feature fusion pyramid network for multi-classes agriculturalpest detection