106. 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.

---

similar to 105

 

/**
 * 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[] inorder, int[] postorder) {
       
       if(inorder.length==0 || inorder.length!=postorder.length)    return null;
       return helper(inorder, 0, inorder.length-1, postorder, 0, postorder.length-1);
        
    }
    
    private TreeNode helper(int[] in, int s1, int e1, int[] post, int s2, int e2){
        
        if(s1>e1 || s2>e2)  return null;
        
        int val = post[e2];
        TreeNode cur = new TreeNode(val);
        
        // find cur in inorder
        int k = s1;
        while(k<=e1 && in[k]!=val){
            k++;
        }
        
        cur.left = helper(in, s1, k-1, post,s2, s2+ k-s1 -1);
        cur.right = helper(in, k+1, e1, post, s2+k-s1, e2-1);
        
        return cur;
        
    }
}

 

posted @ 2013-10-03 09:33  LEDYC  阅读(164)  评论(0)    收藏  举报