sourcecode

Friday, November 23, 2012

Construct Binary Tree from Inorder and Postorder Traversal

http://www.leetcode.com/onlinejudge

/**This one passed both small and large judge.
1. Find the root : Last element in postorder is the root; 
2. Find the position of the root in inorder.
The best strategy is to count the size of the left tree using inorder,
then use the size to split the postorder.

*/

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
#include <vector>
#include <algorithm>
#include <map>
#include <deque>
#include <array>
#include <iostream>

using namespace std;
struct TreeNode {
      int val;
      TreeNode *left;
      TreeNode *right;
      TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 };
class Solution {
public:
    inline size_t valuePos(vector<int> const& v, int value){
        return distance(v.begin(),find(v.begin(), v.end(), value));
    }
    
    TreeNode* build(vector<int> const& inorder, int const in_first, int const in_last,
      vector<int> const& postorder, int const post_first, int const post_last){
          if (post_last-post_first < 0) return NULL;
          TreeNode* root = new TreeNode(postorder[post_last]);
          if (post_last - post_first == 0) return root;
          size_t const r_in = valuePos(inorder, root->val);//can narrow down the search range
          size_t const sizeL = r_in - in_first;
          root->left = build(inorder, in_first, r_in-1,
            postorder, post_first, post_first+sizeL-1);
          root->right = build(inorder, r_in+1, in_last,
            postorder, post_first+sizeL, post_last-1);
          return root;
      }
    
    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (inorder.empty()) return NULL;
        return build(inorder, 0, inorder.size()-1,postorder, 0,postorder.size()-1);
    }
};

int main(){
  array<int, 3> a = {1,2,3};
  vector<int> q(a.begin(),a.end());
  vector<int> v(a.rbegin(),a.rend());
  Solution s;
  auto result = s.buildTree(q,v);
  cout<<result->val<<endl;
  return 0;
  
}

No comments: