public TreeNode buildTree(int[] inorder, int[] postorder) {
if(inorder == null || postorder == null)
return null;
int iLength = inorder.length;
int pLength = postorder.length;
if(iLength == 0 || pLength == 0)
return null;
return buildNode(inorder,0,iLength-1,postorder,0,pLength-1);
}
public TreeNode buildNode(int[] inorder, int iB, int iE, int[] postorder, int pB, int pE) {
if(iB == iE){
TreeNode node = new TreeNode(inorder[iB]);
return node;
}else if(iB > iE)
return null;
TreeNode root = new TreeNode(postorder[pE]);
int index = findIndex(inorder,iB,iE,postorder[pE]);
int llength = index - iB;
int leftBeginIn = iB;
int leftEndIn = index - 1;
int leftBeginPost = pB;
int leftEndPost = pB + llength - 1;
root.left = buildNode(inorder,leftBeginIn,leftEndIn,postorder,leftBeginPost,leftEndPost);
int rightBeginIn = index + 1;
int rightEndIn = iE;
int rightBeginPost = pB + llength;
int rightEndPost = pE - 1;
root.right = buildNode(inorder,rightBeginIn,rightEndIn,postorder,rightBeginPost,rightEndPost);
return root;
}
public int findIndex(int[] Nums,int iB,int iE,int target){
for(int i = iB; i <= iE; i++){
if(Nums[i] == target)
return i;
}
return -1;
}
方法二:使用哈希表。时间复杂度O(n),空间O(n)
public TreeNode buildTreePostIn(int[] inorder, int[] postorder) {
if (inorder == null || postorder == null || inorder.length != postorder.length)
return null;
HashMap hm = new HashMap();
for (int i=0;ireturn buildTreePostIn(inorder, 0, inorder.length-1, postorder, 0,
postorder.length-1,hm);
}
private TreeNode buildTreePostIn(int[] inorder, int is, int ie, int[] postorder, int ps, int pe,
HashMap hm){
if (ps>pe || is>ie) return null;
TreeNode root = new TreeNode(postorder[pe]);
int ri = hm.get(postorder[pe]);
TreeNode leftchild = buildTreePostIn(inorder, is, ri-1, postorder, ps, ps+ri-is-1, hm);
TreeNode rightchild = buildTreePostIn(inorder,ri+1, ie, postorder, ps+ri-is, pe-1, hm);
root.left = leftchild;
root.right = rightchild;
return root;
}
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder == null || inorder == null)
return null;
int preLength = preorder.length;
int inLength = inorder.length;
HashMap map = new HashMap<>();
for(int i = 0; i < inLength; i++){
map.put(inorder[i], i);
}
return buildNode(preorder,0,preLength-1,inorder,0,inLength-1,map);
}
public TreeNode buildNode(int[] preorder, int pB, int pE, int[] inorder, int iB, int iE,HashMap map){
if(iB > iE)
return null;
if(iB == iE){
TreeNode root = new TreeNode(inorder[iB]);
return root;
}
TreeNode root = new TreeNode(preorder[pB]);
int index = map.get(preorder[pB]);
int length = index - iB;
root.left = buildNode(preorder, pB+1, pB+length, inorder, iB, index-1,map);
root.right = buildNode(preorder, pB+length+1, pE, inorder, index+1, iE,map);
return root;
}