首页 > 其他 > 详细

build tree

时间:2014-04-02 10:30:18      阅读:458      评论:0      收藏:0      [点我收藏+]

有二叉树的前序遍历和后序遍历,构造二叉树

/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
HashMap<Integer,Integer> map = new HashMap<Integer,Integer> ();
for(int i=0;i<inorder.length;i++){
map.put(inorder[i], i);
}

return build(map,preorder,0,preorder.length-1,inorder,0,inorder.length-1);
}
private static TreeNode build(HashMap<Integer,Integer> map, int[] preorder,int ps,int pe,int[] inorder,int is,int ie) {
if(ps>pe) return null;
TreeNode root=new TreeNode(preorder[ps]);
if(ps==pe) return root;
int i=map.get(preorder[ps]);
int leftlength=i-is;
root.left=build(map,preorder,ps+1,ps+leftlength,inorder,is,i-1);
root.right=build(map,preorder,ps+i+1-is,pe,inorder,i+1,ie);
return root;
}
}

build tree,布布扣,bubuko.com

build tree

原文:http://www.cnblogs.com/weilq/p/3638218.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!