从中序与后序遍历序列构造二叉树
先看下图
具体步骤如下:
第一步:如果数组大小为零的话,说明是空节点了。
第二步:如果不为空,那么取后序数组最后一个元素作为节点元素。
第三步:找到后序数组最后一个元素在中序数组的位置,作为切割点
第四步:切割中序数组,切成中序左数组和中序右数组 (顺序别搞反了,一定是先切中序数组)
第五步:切割后序数组,切成后序左数组和后序右数组
第六步:递归处理左区间和右区间
难点:切割区间 此题为左闭右开型(中序数组大小一定是和后序数组大小相同)
定义inorder长度(0,preorder.length) 定义postorder长度(0,postorder.length)
完整代码如下:
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
return buildTree1(inorder,0,inorder.length,postorder,0,postorder.length);
}
private TreeNode buildTree1(int[] inorder,int left,int right,int[] postorder,int pleft,int pright){
if(right-left<1){return null;}
if(right-left==1){return new TreeNode(inorder[left]);}
int rootValue = postorder[pright-1];
TreeNode root = new TreeNode(rootValue);
int rootIndex =0;
for(int i=0;i<right;i++){
if(inorder[i]==rootValue){
rootIndex=i;
break;
}
}
root.left=buildTree1(inorder,left,rootIndex,postorder,pleft,pleft+(rootIndex-left));
root.right=buildTree1(inorder,rootIndex+1,right,postorder,pleft+(rootIndex-left),pright-1);
return root;
}
}
本题也可用左闭右闭型
完整代码如下:
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
return buildTree1(inorder,0,inorder.length-1,postorder,0,postorder.length-1);
}
private TreeNode buildTree1(int[] inorder,int left,int right,int[] postorder,int pleft,int pright){
if(left>right||pleft>pright){return null;}
int rootValue = postorder[pright];
TreeNode root = new TreeNode(rootValue);
int rootIndex =0;
for(int i=0;i<=right;i++){
if(inorder[i]==rootValue){
rootIndex=i;
break;
}
}
root.left=buildTree1(inorder,left,rootIndex-1,postorder,pleft,pleft+(rootIndex-left)-1);
root.right=buildTree1(inorder,rootIndex+1,right,postorder,pleft+(rootIndex-left),pright-1);
return root;
}
}
从前序与中序遍历序列构造二叉树
难点:该题用左闭右闭型
定义preorder长度(0,preorder.length-1) 定义inorder(0,inorder.length-1)
完整代码如下:
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
return buildTree1(preorder,0,preorder.length-1,inorder,0,inorder.length-1);
}
private TreeNode buildTree1(int[] preorder,int left,int right,int[] inorder,int ileft,int iright){
if(left>right||ileft>iright){return null;}
int rootValue =preorder[left];
TreeNode root =new TreeNode(rootValue);
int rootIndex=0;
for(int i=0;i<=iright;i++){
if(inorder[i]==rootValue){
rootIndex =i;
break;
}
}
root.left=buildTree1(preorder,left+1,left+(rootIndex-ileft),inorder,ileft,rootIndex-1);
root.right=buildTree1(preorder,left+(rootIndex-ileft)+1,right,inorder,rootIndex+1,iright);
return root;
}
}