106. Construct Binary Tree from Inorder and Postorder Traversal

 

和105是一样的

 1     public TreeNode buildTree(int[] inorder, int[] postorder) {
 2         if(inorder.length == 0 || postorder.length != inorder.length) {
 3             return null;
 4         }
 5         int len = inorder.length;
 6         return helper(inorder, postorder, 0, len - 1, 0, len - 1);
 7     }
 8     
 9     private TreeNode helper(int[] inorder, int[] postorder, int inStart, int inEnd, int postStart, int postEnd) {
10         if(inStart > inEnd || postStart > postEnd) {
11             return null;
12         }
13         TreeNode root = new TreeNode(postorder[postEnd]);
14         int rootIndex = indexOf(inorder, postorder[postEnd]);
15         int leftLen = rootIndex - inStart;
16         int rightLen = inEnd - rootIndex;
17         root.left = helper(inorder, postorder, inStart, rootIndex - 1, postStart, postStart + leftLen - 1);
18         root.right = helper(inorder, postorder, rootIndex + 1, inEnd, postEnd - rightLen, postEnd - 1);
19         return root;
20     }
21     
22     private int indexOf(int[] arr, int key) {
23         for(int i = 0; i < arr.length; i++) {
24             if(arr[i] == key) {
25                 return i;
26             }
27         }
28         return -1;
29     }

 

posted @ 2016-06-10 05:07  warmland  阅读(101)  评论(0编辑  收藏  举报