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后
	}
}
相关推荐
翔云API7 分钟前
人证合一接口:智能化身份认证的最佳选择
大数据·开发语言·node.js·ocr·php
jimmy.hua7 分钟前
C++刷怪笼(5)内存管理
开发语言·数据结构·c++
xiaobai12 310 分钟前
二叉树的遍历【C++】
开发语言·c++·算法
DieSnowK17 分钟前
[项目][WebServer][Makefile & Shell]详细讲解
开发语言·c++·http·makefile·shell·项目·webserver
Freak嵌入式18 分钟前
全网最适合入门的面向对象编程教程:50 Python函数方法与接口-接口和抽象基类
java·开发语言·数据结构·python·接口·抽象基类
冷凝女子20 分钟前
【QT】基于HTTP协议的网络应用程序
开发语言·qt·http
知识分享小能手23 分钟前
mysql学习教程,从入门到精通,SQL 删除数据(DELETE 语句)(19)
大数据·开发语言·数据库·sql·学习·mysql·数据开发
前端小马28 分钟前
解决IDEA出现:java: 程序包javax.servlet不存在的问题
java·servlet·intellij-idea
鸽芷咕32 分钟前
【Python报错已解决】libpng warning: iccp: known incorrect sRGB profile
开发语言·python·机器学习·bug
白总Server38 分钟前
MongoDB解说
开发语言·数据库·后端·mongodb·golang·rust·php