Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

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

Select an option

Save pdu/4413252 to your computer and use it in GitHub Desktop.
Given inorder and postorder 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) {}
* };
*/
class Solution {
public:
TreeNode *build_(tr1::unordered_map<int, int>& num2id, vector<int>& in, int in_left, int in_right, vector<int>& post, int post_left, int post_right) {
if (in_left > in_right) {
return NULL;
}
TreeNode* node = new TreeNode(post[post_right]);
if (in_left == in_right) {
return node;
}
int in_root_id = num2id[post[post_right]];
int left_len = in_root_id - in_left;
node->left = build_(num2id, in, in_left, in_root_id - 1, post, post_left, post_left + left_len - 1);
node->right = build_(num2id, in, in_root_id + 1, in_right, post, post_left + left_len, post_right - 1);
return node;
}
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
if (inorder.empty()) {
return NULL;
}
tr1::unordered_map<int, int> num2id;
for (int i = 0; i < inorder.size(); ++i) {
num2id[inorder[i]] = i;
}
return build_(num2id, inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() - 1);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment