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

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int findInVector(vector<int> vec, int val){  
        for(int i = 0; i < vec.size(); i++){  
            if(vec[i] == val) return i;  
        }  
          
        return -1;  
    }  
  
    TreeNode *build(int is, int ps, int N, vector<int> &inorder, vector<int> &postorder){  
        if(N == 0) return NULL;  
        int rootvalue = postorder[ps+N-1];  
        TreeNode *root = new TreeNode(rootvalue);  
          
        if(N == 1) return root;  
        int in_index = findInVector(inorder, rootvalue);  
          
        int left_len = in_index - is;  
        int right_len = N - 1 - left_len;  
          
        root -> left = build(is, ps, left_len, inorder, postorder);  
        root -> right = build(is+1+left_len, ps+left_len, right_len, inorder, postorder);  
          
        return root;  
  
    }  
  
   
    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        return build(0, 0, inorder.size(), inorder, postorder); 
    }
};


你可能感兴趣的:(LeetCode)