leetcode -- Construct Binary Tree from Inorder and Postorder Traversal

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

[解题思路]

与上题类似Construct Binary Tree from Preorder and Inorder Traversal 确定左右子树的序列,

递归建立树,唯一不同在于后序遍历,根节点在最后一个元素

 1 /**
 2  * Definition for binary tree
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public TreeNode buildTree(int[] inorder, int[] postorder) {
12         // Start typing your Java solution below
13         // DO NOT write main() function
14         if (postorder == null || inorder == null) {
15             return null;
16         }
17         int postLen = postorder.length;
18         int inLen = inorder.length;
19         if (postLen == 0 || inLen == 0) {
20             return null;
21         }
22 
23         return constructTree(postorder, 0, postLen - 1, inorder, 0, inLen - 1);
24     }
25     
26     public static TreeNode constructTree(int[] postorder, int postStart, int postEnd,
27             int[] inorder, int inStart, int inEnd) {
28         int rootVal = postorder[postEnd];
29         TreeNode root = new TreeNode(rootVal);
30         root.left = null;
31         root.right = null;
32         
33         if(postStart == postEnd && postorder[postStart] == inorder[inStart]){
34             return root;
35         }
36         
37         int i = inStart;
38         for(; i <= inEnd; i++){
39             if(inorder[i] == rootVal){
40                 break;
41             }
42         }
43         int leftLen = i - inStart;
44         if(leftLen > 0){
45             root.left = constructTree(postorder, postStart, postStart + leftLen - 1,
46                     inorder, inStart, i - 1);
47         }
48         if(inEnd > i){
49             root.right = constructTree(postorder, postStart + leftLen, postEnd - 1,
50                     inorder, i + 1, inEnd);
51         }
52         return root;
53     }
54 }

 

posted @ 2013-08-23 10:53  feiling  阅读(308)  评论(0编辑  收藏  举报