Chinaunix首页 | 论坛 | 博客
  • 博客访问: 253824
  • 博文数量: 170
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1709
  • 用 户 组: 普通用户
  • 注册时间: 2014-05-06 18:01
文章分类

全部博文(170)

文章存档

2016年(11)

2015年(130)

2014年(29)

分类: Java

2015-10-04 12:46:10

//Given inorder and postorder traversal of a tree, construct the binary tree.
//
//Note:
//You may assume that duplicates do not exist in the tree.
public class ConstructBinaryTreefromInorderandPostorderTraversal {


public static void main(String[] args) {
// TODO Auto-generated method stub


}
public TreeNode buildTree(int[] inorder, int[] postorder) {
if(postorder.length==0)
return null;
int count=inorder.length;
TreeNode root=new TreeNode(postorder[count-1]);
int i;

for(i=0;i<count;i++){
if(inorder[i]==postorder[count-1])
break;
}
TreeNode left=create(postorder,0,i-1,inorder,0,i-1);
TreeNode right=create(postorder,i,count-2,inorder,i+1,count-1);
root.left=left;
root.right=right;
return root;
    }
private TreeNode create(int[] postorder, int s, int e, int[] inorder, int si, int ei) {
// TODO Auto-generated method stub
//没有元素了
if(s>e)
return null;
TreeNode root=new TreeNode(postorder[e]);
int i;
for(i=si;i<=ei;i++){
if(inorder[i]==postorder[e])
break;
}
TreeNode left=create(postorder,s,s+i-1-si,inorder,si,i-1);
TreeNode right=create(postorder,s+i-si,e-1,inorder,i+1,ei);
root.left=left;
root.right=right;
return root;
}


}

阅读(1025) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

权镜士2015-10-14 14:20:21

牛逼牛逼