您的位置:首页 > 其它

leetcode--ConstructBinaryTreefromInorderandPostorderTraversal

2015-06-15 20:19 513 查看
思路:后序遍历子节点一定在根节点的左边,通过从右往左的遍历可以从根节点到子节点生成二叉树。中序遍历左子节点在根节点的左边,右子节点在根节点的右边。在生成二叉树的时候可以通过中序遍历判断当前节点在二叉树中的位置。

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));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息