Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save pdu/4413311 to your computer and use it in GitHub Desktop.

Select an option

Save pdu/4413311 to your computer and use it in GitHub Desktop.
Given preorder and inorder traversal of a tree, construct the binary tree. Note: You may assume that duplicates do not exist in the tree. http://www.leetcode.com/onlinejudge
#include <tr1::unordered_map>
using namespace std;
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
typedef tr1::unordered_map<int, int> hash_;
class Solution {
public:
TreeNode* build_(hash_& h, vector<int>& pre, int pre_left, int pre_right, vector<int>& in, int in_left, int in_right) {
if (pre_left > pre_right) {
return NULL;
}
TreeNode* nd = new TreeNode( pre[pre_left] );
if (pre_left == pre_right) {
return nd;
}
int in_root_id = h[ pre[pre_left] ];
int left_len = in_root_id - in_left;
nd->left = build_(h, pre, pre_left + 1, pre_left + left_len, in, in_left, in_root_id - 1);
nd->right = build_(h, pre, pre_left + left_len + 1, pre_right, in, in_root_id + 1, in_right);
return nd;
}
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
if (inorder.empty()) {
return NULL;
}
hash_ h;
for (int i = 0; i < inorder.size(); ++i) {
h[ inorder[i] ] = i;
}
return build_(h, preorder, 0, preorder.size() - 1, inorder, 0, inorder.size() - 1);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment