题目[题目及部分题解来源与力扣]
给定两个整数数组 inorder 和 postorder ,其中 inorder 是二叉树的中序遍历, postorder 是同一棵树的后序遍历,请你构造并返回这颗 二叉树 。
solution one:
与[剑指offer刷题07](https://blog.csdn.net/qq_36657788/article/details/123843827)思路相似,首先我们要了解什么是中序遍历和后序遍历。- 中序遍历的顺序是每次遍历左孩子,再遍历根节点,最后遍历右孩子。
- 后序遍历的顺序是每次遍历左孩子,再遍历右孩子,最后遍历根节点。
由后续遍历顺序可知,后序序列中最后一个节点一定是根节点,再到中序序列中确定根节点的位置。根节点左侧即为左子树节点,右侧即为右子树节点。所以我们可以确定左、右子树的节点数,这样就可以针对每个部分用同样的方法继续递归下去构造。**注意,这里和给定前序和中序确定树结构不同的是,我们需要先递归遍历右子树,再递归遍历左子树。**
public class inorderPostorderTree {
public int postIndex;
public int findInOrderIndex(int target,int[] inorder,int begin,int end){
for(int i=begin;i<=end;i++){
if(inorder[i]==target)
return i;
}
return -1;
}
public TreeNode createTree(int[] postorder,int[] inorder,int begin,int end){
//如果begin>end,说明子树为空,返回空节点。
if(begin>end) return null;
//找到中序遍历中的根节点的下标
int inIndex=findInOrderIndex(postorder[postIndex],inorder,begin,end);
//如果,没有找到,就返回null
if(inIndex==-1) return null;
//如果找到了,就创建根节点
TreeNode root=new TreeNode(postorder[postIndex]);
//再分别去递归遍历左子树和右子树
postIndex--;
root.right=createTree(postorder,inorder,inIndex+1,end);
root.left=createTree(postorder,inorder,begin,inIndex-1);
return root;
}
public TreeNode buildTree(int[] inorder, int[] postorder) {
if(postorder==null||inorder==null) return null;
postIndex=postorder.length-1;
return createTree(postorder,inorder,0,postorder.length-1);
}
}
solution two:
与[剑指offer刷题07]类似,我们这里给出使用哈希表存储中序序列,即建立一个(元素,下标)键值对的哈希表,以高效查找根节点元素在中序遍历数组中的下标。public class inorderPostorderTree1 {
int post_idx;
int[] postorder;
int[] inorder;
Map<Integer, Integer> idx_map = new HashMap<Integer, Integer>();
public TreeNode helper(int in_left, int in_right) {
// 如果这里没有节点构造二叉树了,就结束
if (in_left > in_right) {
return null;
}
// 选择 post_idx 位置的元素作为当前子树根节点
int root_val = postorder[post_idx];
TreeNode root = new TreeNode(root_val);
// 根据 root 所在位置分成左右两棵子树
int index = idx_map.get(root_val);
// 下标减一
post_idx--;
// 构造右子树
root.right = helper(index + 1, in_right);
// 构造左子树
root.left = helper(in_left, index - 1);
return root;
}
public TreeNode buildTree(int[] inorder, int[] postorder) {
this.postorder = postorder;
this.inorder = inorder;
// 从后序遍历的最后一个元素开始
post_idx = postorder.length - 1;
// 建立(元素,下标)键值对的哈希表
int idx = 0;
for (Integer val : inorder) {
idx_map.put(val, idx++);
}
return helper(0, inorder.length - 1);
}
}