106. 从中序与后序遍历序列构造二叉树
给定两个整数数组 inorder 和 postorder ,其中 inorder 是二叉树的中序遍历, postorder 是同一棵树的后序遍历,请你构造并返回这颗 二叉树 。
示例 1:
输入:inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
输出:[3,9,20,null,null,15,7]
示例 2:
输入:inorder = [-1], postorder = [-1]
输出:[-1]
提示:
1 <= inorder.length <= 3000
postorder.length == inorder.length
-3000 <= inorder[i], postorder[i] <= 3000
inorder 和 postorder 都由 不同 的值组成
postorder 中每一个值都在 inorder 中
inorder 保证是树的中序遍历
postorder 保证是树的后序遍历
题解:
同2月20日每日一题,使用递归分治,对每个子树的中序和后序序列分别处理即可,具体思路可见北邮复试刷题105. 从前序与中序遍历序列构造二叉树__递归分治 (力扣每日一题);
代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
Map<Integer,Integer> map;
public TreeNode buildTree(int[] inorder, int[] postorder) {
map = new HashMap<>();
for(int i=0;i<inorder.length;i++){
map.put(inorder[i],i);
}
return myBuildTree(inorder,postorder,0,inorder.length-1,0,postorder.length-1);
}
public TreeNode myBuildTree(int[] inorder,int[] postorder,int inStart,int inEnd,
int postStart,int postEnd){
// 递归边界,因某子树中序序列与后序序列长度相同 故选择一种判断即可
if(inStart > inEnd){
return null;
}
TreeNode res = new TreeNode(postorder[postEnd]);
int post_in_inorder = map.get(postorder[postEnd]);
int placeLeft = post_in_inorder-1 - inStart;
res.left = myBuildTree(inorder,postorder,inStart,post_in_inorder-1,postStart,placeLeft+postStart);
int placeRight = inEnd - (post_in_inorder+1);
res.right = myBuildTree(inorder,postorder,post_in_inorder+1,inEnd,postEnd-1-placeRight,postEnd-1);
return res;
}
}