/**
* 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)return NULL;
TreeNode* node=new TreeNode(pre[0]);
int p=0;
for(p=0;p<pre.size();p++)
{
if(vin[p]==pre[0])break;
}
vector<int> pre_left,pre_right,vin_left,vin_right;
for(int i=0;i<pre.size();i++)
{
if(i<p)
{
pre_left.push_back(pre[i+1]);
vin_left.push_back(vin[i]);
}
else if(i>p){
pre_right.push_back(pre[i]);
vin_right.push_back(vin[i]);
}
}
node->left=reConstructBinaryTree(pre_left,vin_left);
node->right=reConstructBinaryTree(pre_right,vin_right);
return node;
}
};
重建二叉树
最新推荐文章于 2022-05-26 16:40:57 发布