# 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;
}
};

• 本文已收录于以下专栏：

举报原因： 您举报文章：Construct Binary Tree from Preorder and Inorder Traversal 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)