leetcode 110: Construct Binary Tree from Inorder and Postorder Traversal

Construct Binary Tree from Inorder and Postorder Traversal Sep 30 '12

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

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

 

 

/**
 * 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) {
        // Start typing your Java solution below
        // DO NOT write main() function
        
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(int i=0; i<inorder.length; i++) {
            map.put( inorder[i], i);
        }
        
        return buildRec(map, inorder, 0, inorder.length-1, postorder, 0, postorder.length-1);
    }
    
    private TreeNode buildRec(HashMap<Integer,Integer> map, int[] inorder, int is, int ie, int[] postorder, int ps, int pe) {
        if(is>ie) return null;
        TreeNode root = new TreeNode(postorder[pe]);
        
        if(is==ie) return root;
        int i = map.get( postorder[pe] );
        int leftLength = i-is;
        
        root.left = buildRec(map, inorder, is, i-1, postorder, ps, ps+i-is-1);
        root.right = buildRec(map, inorder, i+1, ie, postorder, ps+i-is, pe-1);
        return root;
    }
}


 

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
/*        4
       3 6
      1  5 7
      
      134567 135764
*/     
     
     unordered_map<int, int> imap;
     int sz = inorder.size();
     
     for(int i=0; i<inorder.size(); i++) {
          imap[inorder[i]] = i;
     }
      
     TreeNode* root = buildRec(imap, inorder, 0, sz-1, postorder, 0, sz-1);
     return root;
    }

private:
    TreeNode* buildRec(unordered_map<int,int>& imap, vector<int>& inorder, int low1, int high1, vector<int>& postorder, int low2, int high2) {
        if(low2>high2) return NULL;
        
        int x = postorder[high2];
        TreeNode* root = new TreeNode(x);
        
        int left_len = imap[x] - low1;
        //int right_len = high1 - imap[x];
        
        root->left = buildRec(imap,inorder, low1, imap[x]-1,postorder, low2, low2+left_len-1); 
        root->right = buildRec(imap, inorder, imap[x]+1, high1, postorder, low2+left_len, high2-1);
        
        
    } 
    
};


你可能感兴趣的:(leetcode 110: Construct Binary Tree from Inorder and Postorder Traversal)