题目的意思是给出一颗二叉树的前序遍历和中序遍历,让你构建出这颗二叉树
只要观察出针对每一颗子树的处理都是相同的,就可以知道这是典型的考察分治的题目,这题也就迎刃而解了。
/**
* 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* reConstructBinaryTree(vector<int> pre, vector<int> vin) {
if (pre.size() == 0||vin.size()==0)//空树,满足条件覆盖和更强的覆盖
return NULL;
TreeNode* root = new TreeNode(pre[0]);
vector<int>::iterator v_itor = vin.begin();
size_t cnt = 0;
while (*v_itor != pre[0])
{
++v_itor;//找到分治的中间点
++cnt;//计数
}
root->left = reConstructBinaryTree(vector<int>(pre.begin() + 1, pre.begin() + cnt + 1), vector<int>(vin.begin(), vin.begin() + cnt));
root->right = reConstructBinaryTree(vector<int>(pre.begin()+cnt+1,pre.end()), vector<int>(vin.begin()+cnt+1,vin.end()));
return root;
}
};