思路:后序遍历前面的节点一定是后面的节点的子节点,因此从后往前遍历可以从根节点向下构造出二叉树。中序遍历左子节点一定在根节点的左边,而右子节点一定在根节点的右边。因此可以通过中序遍历来判断当前节点在树中的位置。
import java.util.HashMap;
/**
* Created by marsares on 15/6/15.
*/
public class ConstructBinaryTreefromInorderandPostorderTraversal {
HashMap<Integer,Integer>hm=new HashMap<Integer,Integer>();
public TreeNode buildTree(int[] inorder, int[] postorder) {
if(postorder.length==0)return null;
if(postorder.length==1)return new TreeNode(postorder[0]);
for(int i=0;i<inorder.length;i++){
hm.put(inorder[i],i);
}
TreeNode root=new TreeNode(postorder[postorder.length-1]);
for(int i=postorder.length-2;i>=0;i--){
root=traversal(postorder[i],root);
}
return root;
}
public TreeNode traversal(int val,TreeNode root){
if(root==null)return new TreeNode(val);
else if(hm.get(val)>hm.get(root.val))root.right=traversal(val,root.right);
else root.left=traversal(val,root.left);
return root;
}
public static void main(String[]args){
ConstructBinaryTreefromInorderandPostorderTraversal cbt=new ConstructBinaryTreefromInorderandPostorderTraversal();
BinaryTreeSerialize bts=new BinaryTreeSerialize();
int[]inorder={4,2,5,1,6,3};
int[]postorder={4,5,2,6,3,1};
TreeNode root=cbt.buildTree(inorder,postorder);
System.out.println(bts.Serialize(root));
}
}