当前位置:网站首页>已知中序遍历数组和先序遍历数组,返回后序遗历数组
已知中序遍历数组和先序遍历数组,返回后序遗历数组
2022-08-02 00:01:00 【小卢要刷力扣题】
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
如果只给定一个二叉树前序遍历数组pre和中序遍历数组in,
能否不重建树,而直接生成这个二叉树的后序数组并返回
已知二叉树中没有重复值
解题思路
定义f函数void类型
把先序遍历数组,跟范围L1, R1.
把中序遍历数组,跟范围L2, R2
填后序遍历数组,范围L3, R3,三段范围等长在中序遍历定位X确定左树跟右树规模
但定位了前序,中序,后序的X后
调用递归,生成左树,右树
代码
public static int[] preInToPos1(int[] pre, int[] in) {
if (pre == null || in == null || pre.length != in.length) {
return null;
}
int N = pre.length;
int[] pos = new int[N];
process1(pre, 0, N - 1, in, 0, N - 1, pos, 0, N - 1);
return pos;
}
// L1...R1 L2...R2 L3...R3
public static void process1(int[] pre, int L1, int R1, int[] in, int L2, int R2, int[] pos, int L3, int R3) {
if (L1 > R1) {
return;
}
if (L1 == R1) {
pos[L3] = pre[L1];
return;
}
pos[R3] = pre[L1];
int mid = L2;
for (; mid <= R2; mid++) {
if (in[mid] == pre[L1]) {
break;
}
}
int leftSize = mid - L2;
process1(pre, L1 + 1, L1 + leftSize, in, L2, mid - 1, pos, L3, L3 + leftSize - 1);
process1(pre, L1 + leftSize + 1, R1, in, mid + 1, R2, pos, L3 + leftSize, R3 - 1);
}
使用哈希表来代替遍历查找过程
public static int[] zuo(int[] pre, int[] in) {
if (pre == null || in == null || pre.length != in.length) {
return null;
}
int N = pre.length;
HashMap<Integer, Integer> inMap = new HashMap<>();
for (int i = 0; i < N; i++) {
inMap.put(in[i], i);
}
int[] pos = new int[N];
func(pre, 0, N - 1, in, 0, N - 1, pos, 0, N - 1, inMap);
return pos;
}
public static void func(int[] pre, int L1, int R1, int[] in, int L2, int R2, int[] pos, int L3, int R3,
HashMap<Integer, Integer> inMap) {
if (L1 > R1) {
return;
}
if (L1 == R1) {
pos[L3] = pre[L1];
} else {
pos[R3] = pre[L1];
int index = inMap.get(pre[L1]);
func(pre, L1 + 1, L1 + index - L2, in, L2, index - 1, pos, L3, L3 + index - L2 - 1, inMap);
func(pre, L1 + index - L2 + 1, R1, in, index + 1, R2, pos, L3 + index - L2, R3 - 1, inMap);
}
}```
边栏推荐
猜你喜欢
随机推荐
How to get the best power efficiency in Windows 11?
Excel表格数据导入MySQL数据库
QML包管理
带你搞懂MySQL隔离级别,两个事务同时操作同一行数据会怎样?
很多人喜欢用多御安全浏览器,竟是因为这些原因
Cash Ⅱ LeetCode_518_ change
Keepalived 高可用的三种路由方案
Study Notes: The Return of Machine Learning
【Leetcode】2360. Longest Cycle in a Graph
【ACWing】406. 放置机器人
Deliver cloud-native microservices applications with Zadig
Docker搭建Mysql主从复制
Axure tutorial - the new base (small white strongly recommended!!!)
JSP如何使用request获取当前访问者的真实IP呢?
一个有些意思的项目--文件夹对比工具(一)
【Leetcode】479. Largest Palindrome Product
@Scheduled注解详解
Thinkphp 5.0.24变量覆盖漏洞导致RCE分析
一篇永久摆脱Mysql时区错误问题,idea数据库可视化插件配置
yay 报错 response decoding failed: invalid character ‘<‘ looking for beginning of value;