cbangchen
11/10/2018 - 5:55 PM

## 105. Construct Binary Tree from Preorder and Inorder Traversal - DifficultyMedium - 2018.9.12

``````/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int findTargetNumIndex(vector<int>& inorder, int num) {
for (int i = 0; i < inorder.size(); i++) {
if (num == inorder[i]) {
return i;
}
}
return -1;
}
TreeNode* buildPartTree(vector<int>& inorder, int iL, int iR, vector<int>& preorder, int pL, int pR) {
if (iL < 0 || iL > iR || iR >= inorder.size() || pL < 0 || pL > pR || pR > preorder.size()) {
return NULL;
}

int mid = preorder[pL];
TreeNode *re = new TreeNode(mid);
int midIndex = findTargetNumIndex(inorder, mid);

re->left = buildPartTree(inorder, iL, midIndex-1, preorder, pL+1, midIndex-iL+pL);
re->right = buildPartTree(inorder, midIndex+1, iR, preorder, midIndex-iL+pL+1, pR);
return re;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
return buildPartTree(inorder, 0 , inorder.size()-1, preorder, 0, preorderv.size()-1);
}
};``````