Java实现Leetcode题(二叉树-3)

Leetcode106(从中序与后序遍历序列构造二叉树)

java 复制代码
package tree;

import java.util.HashMap;
import java.util.Map;

public class LeetCode106 {

	public static void main(String[] args) {
		
	}
	public static TreeNode buildTree(int[] inorder,int[] postorder) {
		Map<Integer,Integer> map = new HashMap<>();
		for(int i = 0;i<inorder.length;i++) {
			map.put(inorder[i], i); //将中序的值和索引
		}
		return travelWay(inorder,0,inorder.length,postorder,0,postorder.length,map);
	}
	//9-3-15-20-7 中
	//9-5-7-20-3  后
	public static TreeNode travelWay(int[] inorder,int inBegin,int inEnd,int[] postorder,int postBegin,int postEnd,Map<Integer,Integer> map) {
		if(inBegin>=inEnd||postBegin>=postEnd) {
			return null;
		} //不满足左闭右开,说明没有元素
		int rootIndex = map.get(postorder[postEnd-1]); //找到结点的索引值
		TreeNode root = new TreeNode(inorder[rootIndex]); //获取结点的数值
		int lenOfleft = rootIndex-inBegin;
		root.left = travelWay(inorder,inBegin,rootIndex,postorder,postBegin,lenOfleft,map); //左中 左后
		root.right = travelWay(inorder,rootIndex+1,inEnd,postorder,postBegin+lenOfleft,postEnd-1,map); //右中 右后
		return root;

}
}

Leetcode105(从前序与中序遍历序列构造二叉树)

java 复制代码
package tree;

import java.util.HashMap;
import java.util.Map;

public class Leetcode105 {
	public static void main(String[] args) {
		
	}
	public static TreeNode findWay(int[] prorder,int[] inorder) {
		Map<Integer,Integer> map = new HashMap<>();
		for(int i =0;i<inorder.length;i++) {
			map.put(inorder[i], i);
		}
		return travelWay(prorder,0,prorder.length,inorder,0,inorder.length,map);
	}
	public static TreeNode travelWay(int[] preorder,int prebegin,int preend,int[] inorder,int inbegin,int inend,Map<Integer,Integer> map) {
		if(prebegin>=preend||inbegin>=inend) {
			return null;
		}
		int rootIndex = map.get(preorder[0]);
		TreeNode root = new TreeNode(inorder[rootIndex]);
		int preofLeft = rootIndex-prebegin;
		//3 9 20 15 7前
		//9 3 15 20 7中
		root.left = travelWay(preorder,prebegin+1,prebegin+preofLeft+1,inorder,inbegin,rootIndex,map);//左前序,左中序
		root.right = travelWay(preorder,prebegin+preofLeft+1,preend,inorder,rootIndex+1,inend,map);
		return root;
		//5 4 1 2 6 7 8前
		//1 4 2 5 7 6 8中
		//1 2 4 7 8 6 5后
	}
}
相关推荐
Alan521595 分钟前
Java 使用 Quartz 实现定时任务(超简单入门)
java
有来技术29 分钟前
全栈架构后端攻坚:基于 youlai - boot(开源)、Spring Boot 3 与 Spring Security 6 实现企业级权限系统全功能实战手册
java·spring boot·后端
落笔映浮华丶32 分钟前
C++(进阶) 第11智能指针
开发语言·c++
ephemerals__33 分钟前
【c++11】c++11新特性(上)(列表初始化、右值引用和移动语义、类的新默认成员函数、lambda表达式)
开发语言·c++
froginwe1136 分钟前
Scala Iterator(迭代器)
开发语言
雪夜行人44 分钟前
openpyxl合并连续相同元素的单元格
开发语言·python
weixin_445054721 小时前
力扣刷题-热题100题-第34题(c++、python)
c++·python·leetcode
姜行运1 小时前
C++【string类】(一)
android·开发语言·c++
烁3471 小时前
每日一题(小白)暴力娱乐篇23
java·开发语言·算法·娱乐
helloworld_工程师1 小时前
Spring AI应用:利用DeepSeek+嵌入模型+Milvus向量数据库实现检索增强生成--RAG应用(超详细)
java·后端