当前位置:网站首页>JZ7 重建二叉树
JZ7 重建二叉树
2022-07-25 06:16:00 【程序员·小李】
给定节点数为 n 的二叉树的前序遍历和中序遍历结果,请重建出该二叉树并返回它的头结点。
例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建出如下图所示。

前序遍历的顺序是:root -> left -> right
中序遍历的顺序是: left -> root -> right

前序遍历的第一个元素,必定是根节点。在中心遍历中,root前面的必定是左子树,root后面的必定是右子树。
1. 在前序遍历中,找到根节点,即pre[0],初始化前序、中序遍历数组中数据的范围preStart, preEnd, inStart, inEnd

2. 在中序遍历中,找到根节点的位置,rootIndexInVin

3. 那么按照刚刚的原理,我们就可以分别把pre和vin按照数据的长度、左子树的位置确定新的preStart, preEnd, inStart, inEnd

根据root的位置,inStart, inEnd我们可以确定,inStart~rootIndexInVin - 1属于左子树,可以确定左子树的inStart, inEnd

同样的,也可以根据inStart, inEnd我们可以确定,rootIndexInVin + 1 ~ inEnd属于右子树,可以确定右子树的inStart, inEnd

因而,我们计算出,左子树的长度,右子树的长度:


4. 根据左子树和右子树的长度,以及preStart, preEnd计算左右子树在前序遍历中的范围。

我们知道,前序遍历中第一个元素是根节点,因而,从preStart + 1开始,持续len(L)个元素都是左子树,因此,我们可以确认范围
preStart' = preStart + 1
preEnd' = preStart' + len(L) - 1 = (preStart + 1) + leftNodeLength - 1

在左子树范围的基础上,再延后len(R)个元素就是右子树范围
preStart" = preEnd' + 1 = (preStart + 1 + leftNodeLength - 1) + 1
preEnd" = preStart" + len(R) - 1 = (preStart + 1 + leftNodeLength - 1 + 1) + rightNodeLength - 1
好了这样,递归的完成二叉树的重建,直到所有的元素都遍历一遍。
import java.util.*;
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] vin) {
return construct(pre, 0, pre.length - 1, vin, 0, vin.length - 1);
}
private TreeNode construct(int[] pre, int preStart, int preEnd, int[] vin, int inStart, int inEnd){
if (pre == null || pre.length == 0 || vin == null || vin.length == 0){
return null;
}
if (preStart > preEnd || inStart > inEnd){
return null;
}
// 前序遍历的第一个元素就是当前的根节点
int rootVal = pre[preStart];
// 找到在中序遍历的数组中,根节点的位置
int rootIndexInVin = inStart;
while (rootIndexInVin <= inEnd && vin[rootIndexInVin] != rootVal){
rootIndexInVin++;
}
// 根节点的左子树节点总共有:inStart~rootIndexInVin-1
int leftNodeLength = rootIndexInVin - inStart;
int rightNodeLength = inEnd - rootIndexInVin;
TreeNode rootNode = new TreeNode(rootVal);
rootNode.left = construct(pre, preStart + 1, (preStart + 1) + leftNodeLength - 1, vin, inStart, rootIndexInVin - 1);
rootNode.right = construct(pre, (preStart + 1 + leftNodeLength - 1) + 1, (preStart + 1 + leftNodeLength - 1) + 1 + rightNodeLength - 1, vin, rootIndexInVin + 1, inEnd);
return rootNode;
}
}边栏推荐
- GF Securities online account opening? Is it safe?
- What determines the "personality" of AI robots?
- 【luogu P6629】字符串(Runs)(树状数组)
- ARM裸板调试之JTAG调试源码级调试
- Calculate BDP value and wnd value
- R奇怪语法总结
- Special episode of Goddess Festival | exclusive interview with Chinese AI goddess Zhang Qingqing's transformation from a female learning tyrant to a female entrepreneur
- Unity Animator动画与状态机
- [daily practice] day (14)
- 【Node】服务端口被占用Error: listen EADDRINUSE: address already in use :::9000-如何关闭node启动的端口
猜你喜欢
![(14) [driver development] configuration environment vs2019 + wdk10 write XP driver](/img/90/0d94d26be8128d77de65919763fda5.png)
(14) [driver development] configuration environment vs2019 + wdk10 write XP driver

Android interview question: why do activities rebuild ViewModel and still exist—— Jetpack series (3)

(2022 Niuke multi School II) l-link with level editor I (dynamic planning)

Softing pngate series gateway: integrate PROFIBUS bus into PROFINET network

It is said that screentogif is a GIF recording artifact, but I don't know that its strength is far from here

(牛客多校二)G-Link with Monotonic Subsequence(构造题)

【datawhale202207】强化学习:策略梯度和近端策略优化

R奇怪语法总结

ROI pooling and ROI align

"Everyday Mathematics" serial 61: March 1
随机推荐
(Niuke multi School II) j-link with arithmetic progress (least square method / three points)
Review of some classic exercises of arrays
【luogu P6629】字符串(Runs)(树状数组)
(16) [system call] track system call (3 rings)
Singing "Seven Mile fragrance" askew -- pay tribute to Jay
“蔚来杯“2022牛客暑期多校训练营2 Link with Game Glitch (spfa找正负环)
4、 MFC toolbar, runtime class information mechanism, runtime creation mechanism
Leetcode/ integer division
Siggraph 2022 -- rendering iridescent rock dove neck feathers
深度解析:2022年最火的商业模式链动2+1,是合法模式吗?
In depth analysis: is the hottest business model in 2022 linked by 2+1 a legal model?
MySQL queries the table name under the current database
“font/woff“ and “font/woff2“ in file “mime.types“
Memory memory operation function
Sword finger offer 45. arrange the array into the smallest number
Some interview questions collected
函数模板学习记录
Solve the problem of invalid modification of QT 5 interface. Solve the problem of invalid modification of qtdesigner
Unity 模型简化/合并 一键式插件
How to play a data mining game entry Edition