题目:力扣106.从中序与后序遍历序列构造二叉树
根据一棵树的中序遍历与后序遍历构造二叉树。
注意: 你可以假设树中没有重复的元素。
例如,给出中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3] 返回如下的二叉树:
思路分析:
一层一层分割,就应该想到递归。
递归三部曲:(一)确定递归函数的参数和返回值
(二)终止条件
如果区间没有元素,返回空树。
if(inBegin >= inEnd || postBegin >= postEnd) {
return null;
}
(三) 单层递归逻辑:
1、找到后序遍历的最后一个元素在中序数组中的位置,这个元素为切割点
2、构造节点
3、分割中序左数组 中序右数组
4、分割后序左数组、后序右数组
5、递归左区间、右区间 —— 递归函数(中左,后左) 递归函数(中右,后右)
代码:
class Solution {
Map<Integer,Integer> map = new HashMap<>(); ; //用一个map存储中序数组,key:元素值,value:元素在中序数组中的索引
public TreeNode buildTree(int[] inorder, int[] postorder) {
for(int i = 0;i<inorder.length;i++){
map.put(inorder[i],i);
}
return findNode(inorder,0,inorder.length,postorder,0,postorder.length);
}
//层层分割,想到了用递归,递归三部曲
//(一)确定递归函数的参数和返回值 参数含义:原始的中序数组,划分的中序数组开始位置索引,划分的中序数组结束位置索引。左闭右开
//原始的后序数组,划分的后序数组开始位置索引,划分的后序数组结束位置索引
//返回值:是二叉树中的节点,包含要素:节点的值,以及左子树、右子树。
public TreeNode findNode(int[] inorder,int inBegin,int inEnd,int[] postorder,int postBegin,int postEnd){
//(二) 终止条件--不满足左闭右开,说明没有元素,返回空树
if(inBegin >= inEnd || postBegin >= postEnd) {
return null;
}
//(三) 单层递归的逻辑
//1、找到后序遍历的最后一个元素在中序数组中的位置,这个元素为切割点
int rootIndex = map.get(postorder[postEnd-1]);
//2、构造节点
TreeNode root = new TreeNode(inorder[rootIndex]);
//左子树的个数
int lenOfLeft = rootIndex - inBegin;
//3、分割中序左数组 中序右数组
//中序左数组索引:(左闭右开) [inBegin,rootIndex) 中序右数组索引:[rootIndex+1,inEnd)
//4、分割后序左数组、后序右数组
//后序左数组索引:(左闭右开) [postBgein,postBegin+lenOfLeft) 后序右数组索引:[postBegin+lenOfLeft,postEnd-1)
//5、递归左区间、右区间
root.left = findNode(inorder,inBegin,rootIndex,postorder,postBegin,postBegin+lenOfLeft);
root.right = findNode(inorder,rootIndex+1,inEnd,postorder,postBegin+lenOfLeft,postEnd-1);
return root;
}
}
构造二叉树:105.从前序与中序遍历序列构造二叉树
题目:
给定两个整数数组 preorder
和 inorder
,其中 preorder
是二叉树的先序遍历, inorder
是同一棵树的中序遍历,请构造二叉树并返回其根节点。
class Solution {
Map<Integer,Integer> map = new HashMap<>();
public TreeNode buildTree(int[] preorder, int[] inorder) {
for(int i = 0;i<inorder.length;i++){
map.put(inorder[i],i);
}
return findNode(preorder, 0,preorder.length,inorder,0,inorder.length);
}
public TreeNode findNode(int[] preorder,int ps,int pe, int[] inorder,int is,int ie){
if(ps>=pe || is>=ie){
return null;
}
//找到先序数组第一个元素在中序数组中的位置索引,作为分割点
int rootIndex = map.get(preorder[ps]);
TreeNode root = new TreeNode(inorder[rootIndex]);
//左子树数组长度
int lenLeft = rootIndex -is;
//划分先序左数组 [ps+1,ps+1+lenLeft) 先序右数组[ps+1+lenLeft,pe)
//划分中序左数组 [is, rootIndex ) 中序右数组 [rootIndex+1,ie)
root.left = findNode(preorder,ps+1,ps+1+lenLeft,inorder,is, rootIndex);
root.right = findNode(preorder,ps+1+lenLeft,pe,inorder,rootIndex+1,ie);
return root;
}
}