一、题目描述
给定两个整数数组 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]
二、解题
找四个节点
/**
* 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 = new HashMap<>();
public TreeNode buildTree(int[] inorder, int[] postorder) {
//这与前序遍历和中序遍历构造二叉树相似
//主要找四个节点 使用hashMap保存中序遍历的节点
if(inorder == null || postorder == null || inorder.length == 0 || postorder.length == 0){
return null;
}
//保存中序遍历的节点
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 ileft,int iright,int pleft,int pright){
//判断数组
if(ileft > iright || pleft > pright){
return null;
}
//找到根节点
int rootnum = postorder[pright];
//创建根节点
TreeNode root = new TreeNode(rootnum);
//分割数组
int inorderindex = map.get(rootnum);
//左子树的长度
int leftlength = inorderindex - ileft;
//后序遍历的下一个分段
root.left = myBuildTree(inorder,postorder,ileft,inorderindex-1,pleft,pleft+leftlength-1);
root.right = myBuildTree(inorder,postorder,inorderindex+1,iright,pleft+leftlength,pright-1);
return root;
}
}