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后
	}
}
相关推荐
寻星探路1 分钟前
【Python 全栈测开之路】Python 进阶:库的使用与第三方生态(标准库+Pip+实战)
java·开发语言·c++·python·ai·c#·pip
求梦8202 小时前
【力扣hot100题】旋转图像(15)
算法·leetcode·职场和发展
海边的Kurisu3 小时前
苍穹外卖日记 | Day1 苍穹外卖概述、开发环境搭建、接口文档
java
C雨后彩虹6 小时前
任务最优调度
java·数据结构·算法·华为·面试
heartbeat..6 小时前
Spring AOP 全面详解(通俗易懂 + 核心知识点 + 完整案例)
java·数据库·spring·aop
Jing_jing_X6 小时前
AI分析不同阶层思维 二:Spring 的事务在什么情况下会失效?
java·spring·架构·提升·薪资
SmartRadio8 小时前
CH585M+MK8000、DW1000 (UWB)+W25Q16的低功耗室内定位设计
c语言·开发语言·uwb
rfidunion8 小时前
QT5.7.0编译移植
开发语言·qt
rit84324998 小时前
MATLAB对组合巴克码抗干扰仿真的实现方案
开发语言·matlab
元Y亨H8 小时前
Nacos - 服务发现
java·微服务