# Construct Binary Tree from Preorder and Inorder Traversal

Given preorder and inorder traversal of a tree, construct the binary tree.

       if(pre_begin > preorder.size() - 1 || in_begin > in_end) return NULL;

/**
* 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:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
return creatTree(0, 0, inorder.size() - 1, preorder, inorder);
}
TreeNode* creatTree(int pre_begin, int in_begin, int in_end, vector<int>& preorder, vector<int>& inorder){
if(pre_begin > preorder.size() - 1 || in_begin > in_end) return NULL;
TreeNode *root = new TreeNode(preorder[pre_begin]);
int index = 0;
for (int i = in_end; i >= in_begin; --i) {
if (inorder[i] == root -> val) {
index = i;
break;
}
}
root -> left = creatTree(pre_begin + 1, in_begin, index - 1, preorder, inorder);
root -> right = creatTree(pre_begin + index - in_begin + 1, index + 1, in_end, preorder, inorder);
return root;
}
};

06-01 6865

05-21 3878

04-24 1.8万

08-09 2750

11-30 1430

07-30 447

11-12 2405

12-04 673

08-09 2497

04-24 1.2万