Construct Binary Tree from Inorder and Postorder Traversal

 1 public class Solution {
 2     public TreeNode buildTree(int[] inorder, int[] postorder) {
 3         int inEnd = inorder.length-1;
 4         int postEnd = postorder.length-1;
 5         if(inEnd<0 || postEnd<0) return null;
 6         return build(inorder,0,inEnd,postorder,0,postEnd);
 7     }
 8     public TreeNode build(int []in,int inStart,int inEnd,int[]post,int postStart,int postEnd){
 9         TreeNode root = new TreeNode(post[postEnd]);
10         root.left = null;
11         root.right = null;
12         if(postStart == postEnd && post[postStart] == in[inStart]) return root;
13         int piv = inStart;
14         for(;piv<=inEnd;piv++){
15             if(in[piv]==post[postEnd]) break;
16         }
17         int leftLen = piv-inStart;
18         if(leftLen>0)
19             root.left = build(in,inStart,piv-1,post,postStart,postStart+leftLen-1);
20         if(piv<inEnd)
21             root.right = build(in,piv+1,inEnd,post,postStart+leftLen,postEnd-1);
22         return root;
23     }
24 }
View Code

  if(preS>preE || inS>inE) return null;

posted @ 2014-02-12 04:08  krunning  阅读(114)  评论(0编辑  收藏  举报