当前位置:网站首页>【JZOF】07 重建二叉树
【JZOF】07 重建二叉树
2022-07-23 05:56:00 【叹了口丶气】

这里记录一下左子树的前序截止下标是怎么计算出来的吧。方便以后速度回想起来:
假设这个下标是X。那么有如下等式:
i - inStart = X - preStart;
因此:
X = preStart - inStart + i;
这个下标计算出来之后,其他的下标都很简单了。
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 [] in) {
TreeNode root=reConstructBinaryTree(pre, 0, pre.length - 1, in, 0, in.length - 1);
return root;
}
//前序遍历{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6}
private TreeNode reConstructBinaryTree(int [] pre,int startPre,int endPre,int [] in,int startIn,int endIn) {
if(startPre>endPre||startIn>endIn)
return null;
TreeNode root=new TreeNode(pre[startPre]);
for(int i=startIn;i<=endIn;i++)
if(in[i]==pre[startPre]) {
root.left=reConstructBinaryTree(pre,startPre+1,startPre+i-startIn,in,startIn,i-1);
root.right=reConstructBinaryTree(pre,i-startIn+startPre+1,endPre,in,i+1,endIn);
break;
}
return root;
}
}
边栏推荐
- linx的链接、一级目录、重定向、cp与mv
- 雷达导论PART VII.3 SAR图像的形成和处理
- 聊聊研发团队中的“人”
- C语言-大端存储和小端存储
- How does redis implement persistence? Explain in detail the three triggering mechanisms of RDB and their advantages and disadvantages, and take you to quickly master RDB
- 信号完整性(SI)电源完整性(PI)学习笔记(三十二)电源分配网路(四)
- OSPF multi area configuration instance learning record
- 4D毫米波雷达硬件系统架构
- Prefix and leetcode2100. Suitable for bank robbery days
- TI单芯片毫米波雷达1642代码走读(〇)——总纲
猜你喜欢

Solution rapide: xshell ne peut pas glisser dans un dossier ou un paquet

Numpy:基本操作快速入门

高压MOS管KNX42150 1500V/3A 应用于变频器电源-逆变器等

FTP configuration instance learning record

linx的链接、一级目录、重定向、cp与mv

Pod topology constraints

Why build a local Yum warehouse?

In the Internet era, how to refine user operations?

在GPU上运行MATLAB程序

录入数学公式至mark down文档的方法
随机推荐
[ACTF2020 新生赛]BackupFile 1
Static route configuration instance learning record
0 dynamic programming leetcode918. Maximum sum of circular subarrays
Rhcsa - - parcourir le contenu du fichier, couper, uniq, trier, utiliser les commandes.tr
C语言-大端存储和小端存储
ACL访问控制实验
Paging collections using streams
TI单芯片毫米波雷达1642代码走读(〇)——总纲
时间复杂度总结(Ο是渐进上界,Ω是渐进下界,p,np,np-hard,NPC问题)
NFS service deployment notes
转行软件测试有学历要求吗?低于大专是真的没出路吗?
ACL access control experiment
Why build a local Yum warehouse?
C # enter a letter and judge its case
在GPU上运行MATLAB程序
TI单芯片毫米波雷达代码走读(二十五)—— 角度维(3D)处理流程
Count different types of data according to different times (stored procedures)
RHCSA--文件内容浏览、cut、uniq、sort、.tr命令使用
How to prevent repeated payment of orders?
0 double pointer leetcode844. Compare strings with backspace