【LeetCode106】Construct Binary Tree from Inorder and Postorder Traversal★★
2024-10-18 18:27:40
1.题目
2.思路
思路和LeetCode105类似,见上篇。
3.java代码
//测试
public class BuildTreeUsingInorderAndPostorder {
public static void main(String[] args) {
int[] postSort={7,4,2,5,8,6,3,1};
int[] inSort={4,7,2,1,5,3,8,6};
System.out.println(new Solution2().buildTree(postSort, inSort));
}
}
//利用中序和后序重建二叉树
class Solution2 {
public TreeNode buildTree(int[] inorder, int[] postorder) {
//参数校验
if(postorder==null||inorder==null||postorder.length!=inorder.length||postorder.length==0)
return null;
return buildTreeCore(inorder,0,inorder.length-1,postorder,0,postorder.length-1);
}
/**
* 构建二叉树,数据输入的正确性由输入数据自己保证
*
* @param postorder 后序遍历的结果
* @param startPostorder 后序遍历的开始位置
* @param endPostorder 后序遍历的结束位置
* @param inorder 中序遍历的结果
* @param startInorder 中序遍历的开始位置
* @param endInorder 中序遍历的结束位置
* @return 二叉树的根结点
*/
private TreeNode buildTreeCore(int[] inorder,int startInorder, int endInorder,
int[] postorder, int startPostorder, int endPostorder) {
// 只有一个元素时直接返回该节点,这也是递归结束的出口标志
if(startPostorder==endPostorder){
return new TreeNode(postorder[endPostorder]);
}else{
// 记录根结点的在中序遍历中的位置
int rootIn=startInorder;
for(int i=startInorder;i<=endInorder;i++){
if(inorder[i]==postorder[endPostorder]){
rootIn=i;
break;
}
}
// 创建根结点
TreeNode root=new TreeNode(inorder[rootIn]);
// 左子树的结点个数
int leftLength=rootIn-startInorder;
if(leftLength>0){
// startPostorder, startPostorder+leftLength-1:左子树在后序序列中的起始和结束位置
root.left=buildTreeCore(inorder, startInorder, rootIn-1, postorder, startPostorder, startPostorder+leftLength-1);
}
// 右子树的结点个数
int rightLength=endInorder-rootIn;
if(rightLength>0){
// startPostorder+leftLength, endPostorder:左子树在后序序列中的起始和结束位置
root.right=buildTreeCore(inorder, rootIn+1, endInorder, postorder, startPostorder+leftLength, endPostorder-1);
}
return root;
}
}
}
//二叉树节点定义
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
最新文章
- grunt任务之seajs模块打包
- Web 在线文件管理器学习笔记与总结(9)下载文件
- C++中的虚继承 &; 重载隐藏覆盖的讨论
- break 和 continue
- Word Ladder II 解答
- PyCharm 2016.1 for Mac 激活方法分享
- Idea高级用法
- 《Intel汇编第5版》 汇编减法程序
- laravel怎么创建一个简单的blog
- Windows Server 2012 删除IIS之后 重新启动 桌面不出来 只出现一个命令提示框 解决方法
- css 效果之转换
- ThemeableBrowser在IOS中按钮图片的使用
- python全栈开发day17-常用模块collections,random,time,os,sys,序列化(json pickle shelve)
- 基于VS2017的Docker Support体检ASP.NET Core站点的Docker部署
- libcurl HTTP POST请求向服务器发送json数据
- Kafka参数配置详解
- 设计模式学习——代理模式(Proxy Pattern)之 强制代理(强校验,防绕过)
- Jenkins的Pipeline脚本在美团餐饮SaaS中的实践
- Matlab图形调色
- is和==的区别以及编码、解码
热门文章
- c3p0死锁
- docker第一章:docker核心概念及centos6下安装
- win7 x64 +vs2015 + cmake3.10.3编译opencv-3.4.1+opencv_contrib-3.4.1源码,并进行配置
- [Spark] Spark 安装配置
- 洗礼灵魂,修炼python(57)--爬虫篇—知识补充—编码之对比不同python版本获取的数据
- 关于Natively Compiled Stored Procedures的优化
- ubuntu16.04系统彻底卸载mysql,并源码免编译重装MySQL的步骤
- linux 下正则匹配时间命名格式的文件夹
- ios 百度地图使用
- iOS解析XML实现省市区选择