菜鸡太菜,所以好些思路书中没有提到,自己想半天搞懂之后,就记录一下吧
在重构二叉树这道题目中
关键:在前序遍历中查找root,结合中序遍历,能够知道左右子树中节点长度递归 root.left 和root.right就可以了。
细节:我认为是inStart,因为我在自己敲代码的时候给搞错了,认为root.left中调用的inStart始终是0
提高:在原解题答案的基础上,改了root.right中 inStart的表达式,因为inStart的主要作用其实是通过中序遍历root的位置计算左右子树的节点长度(表示的可能不专业),所以传递position+1更为简洁易懂。
import java.util.*;
public class Solution {
HashMap<Integer,Integer> hash=new HashMap<>();
public TreeNode reConstructBinaryTree(int[] pre,int [] in) {
for(int i=0;i<in.length;i++){
hash.put(in[i],i);
}
return reconstruct(pre,0,pre.length-1,0);
}
private TreeNode reconstruct(int[] pre,int low,int high,int inStart){
if(low>high)
return null;
TreeNode root = new TreeNode(pre[low]);
//position是中序遍历中root的位置
int position = hash.get(pre[low]);
int lenL = position-len;
//left中的inStart不始终为0,在right中的一个left里,inStart不为0
root.left=reconstruct(pre,low+1,low+lenL,inStart);
//(position+1)是中序遍历root右边的
root.right=reconstruct(pre,low+lenL+1,high,position+1);
return root;
}
}
又写了一次 中序和后序重建二叉树的
import java.util.*;
class Solution {
HashMap<Integer,Integer> hash=new HashMap<>();
public TreeNode buildTree(int[] inorder, int[] postorder) {
for(int i=0;i<inorder.length;i++)
hash.put(inorder[i],i);
return reconstruct(postorder,0,postorder.length-1,0);
}
private TreeNode reconstruct(int[] postorder,int left,int right,int len){
if(left>right)
return null;
TreeNode root=new TreeNode(postorder[right]);
int position=hash.get(postorder[right]);
int length=position-len;
root.left=reconstruct(postorder,left,left+length-1,len);
root.right=reconstruct(postorder,left+length,right-1,position+1);
return root;
}
}