LeetCode106. 从中序与后序遍历序列构造二叉树
题目描述#
给定两个整数数组 inorder 和 postorder ,其中 inorder 是二叉树的中序遍历, postorder 是同一棵树的后序遍历,请你构造并返回这颗 二叉树 。
示例#
提交的代码#
思路:
轻喷,这种还是手写方便。
中序:左中右
后序:左右中
看我上面画的屎图,整棵树的根节点由后序的特性一定是在最后一个,也就是3,然后去中序数组可以确定3在哪,也就确定了整棵树的左子树和右子树有哪些节点,然后根据中序左子树和右子树的长度去确定后序数组中,左子树和右子树的后序遍历是哪些,然后去递归就行。
import java.util.Map;
import java.util.HashMap;
class Solution {
Map<Integer,Integer> map = new HashMap<>();
public TreeNode buildTree(int[] inorder, int[] postorder) {
//用map记录中序数组每个元素对应的索引,方便根据后续的最后一个元素值确定中序的索引,进而划分左右树数组
for(int i=0;i<inorder.length;i++){
map.put(inorder[i],i);
}
return recursiveMethod(inorder,postorder,0,inorder.length-1,0,postorder.length-1);
}
public TreeNode recursiveMethod(int[] inorder, int[] postorder,int inLow,int inHigh,int postLow,
int postHigh){
//递归终止条件
if(inLow>inHigh){
return null;
}
TreeNode node=new TreeNode(postorder[postHigh]);
//根据后序遍历数组的最后一个元素来确定中序数组的索引值(划分左右树数组用)
int inNodeIndex=map.get(postorder[postHigh]);
//确定左子树的元素个数
int leftLength=inNodeIndex-inLow;
//确定右子树的元素个数
int rightLength=inHigh-inNodeIndex;
node.left=recursiveMethod(inorder,postorder,inLow,inNodeIndex-1,postLow,postLow+leftLength-1);
node.right=recursiveMethod(inorder,postorder,inNodeIndex+1,inHigh,postLow+leftLength,postHigh-1);
return node;
}
}
作者:whitePuPigeon
出处:https://www.cnblogs.com/whitePuPigeon/p/17815716.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理