当前位置:网站首页>【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;
}
}
边栏推荐
猜你喜欢

将指定秒转为时分秒格式

功能测试转自动化测试,十年自动化测试经验分享

课程设计-推箱子C#(win form)

快速解决:Xshell拖不進去文件夾或者軟件包的問題

Three layer switching configuration example learning record

踩坑electron渲染进程renderer,解决require is not defined的问题

问题解决:Script file ‘Scripts\pip-script.py‘ is not present.

CORTEX-A系列处理器

zabbix监控详细安装到部署

Quick solution: xshell can't drag into folders or software packages
随机推荐
力扣 剑指 Offer II 094. 最少回文分割
录入数学公式至mark down文档的方法
ACL configuration instance learning record
TI单芯片毫米波雷达1642代码走读(〇)——总纲
Real questions required for Niuke interview [algorithm] summary of high-frequency TOP200 questions
ACL访问控制实验
NFS service deployment notes
tar、sftp、fin的、history命令,变量、别名
The context of virtual memory technology (Part 1)
C randomly generate a score to judge its grade (excellent, good, medium, poor, failed)
MIMO雷达专题(〇)—— 总章
VLAN configuration instance learning record
复杂网络-常用绘图软件和库
Harbor deployment
FTP configuration instance learning record
HCIA----06 OSPF
Unity 模型显示到UI前面,后面的UI抖动
Outlook 教程,如何在 Outlook 中切换日历视图、创建会议?
OpenVPN deployment
快速解决:Xshell拖不進去文件夾或者軟件包的問題