当前位置:网站首页>Reconstruction of binary tree
Reconstruction of binary tree
2022-07-30 00:15:00 【Ryuzaki Liuhe】
题目:
输入某二叉树的前序遍历和中序遍历的结果,请构建该二叉树并返回其根节点.
假设输入的前序遍历和中序遍历的结果中都不含重复的数字.
示例一:
Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]
分析:
find recursion
代码:
import java.util.HashMap;
import java.util.Map;
public class BuildTree {
// Use the hash function to easily get the subscript
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]);
//Get the root node subscript
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;
}
}
边栏推荐
- 月薪15k的阿里测试岗,面试原来这么简单
- ZLMediaKit源码分析 - WebRtc连接迁移
- Low dropout linear regulator MPQ2013A-AEC1 brand MPS domestic replacement
- 【励志】科比精神
- Graph Theory: Bipartite Graphs
- Worthington酶促细胞收获&细胞粘附和收获
- 单片机开发之基本并行I/O口
- WeChat developer tools set the tab size to 2
- i.MX6U-driver development-3-new character driver
- From the perspective: the interviewer interview function test engineer mainly inspects what ability?
猜你喜欢
随机推荐
2022年企业直播行业发展洞察
KDE Frameworks 5.20.0:Plasma迎来诸多改进
2022年ps应该选择哪个版本
vmtouch——Linux下的文件缓存管理神器
ZLMediaKit源码学习——UDP
Worthington细胞分离技术丨基本原代细胞分离方法和材料
4 hotspot inquiry networks necessary for new media operations
Adaptive feature fusion pyramid network for multi-classes agriculturalpest detection
Codeforces Round #805 (Div. 3) Summary
从尾到头打印链表
rk-boot框架实战(1)
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
what is a .pro file in qt
【集训DAY16】ALFA【凸壳】【计算几何】
Worthington解离酶:胰蛋白酶及常见问题
【分层强化学习】survey
Towhee 每周模型
docker安装redis集群(含部署脚本)
对数据库进行增删改查操作
EA & UML Sun Arch - State Diagram :: Redraw Button State Diagram