当前位置:网站首页>【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;
}
}
边栏推荐
猜你喜欢
随机推荐
Quick solution: xshell can't drag into folders or software packages
将集合使用流进行分页
Query the cross compiled executable dependency Library
OpenCV 视频操作
课程设计-推箱子C#(win form)
Plug ins used by Jenkins
雷达导论PART VII.4 SAR系统设计
FTP deployment
Confused, work without motivation? Career development hopeless? It's enough to read this article
迷茫、工作没动力? 职业发展没希望? 看这篇文章就够了
HCIA----05 RIP
Tar, SFTP, fin, history commands, variables, aliases
虚拟内存技术的来龙去脉(上)
Convert the specified seconds to minutes and seconds
Install LNMP service deployment using yum
UI自动化
Static routing principle and configuration
Es common operations
国信证券软件开户是安全吗?信息会不会泄露?
C randomly generate a score to judge its grade (excellent, good, medium, poor, failed)








