/** * 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* p=new TreeNode(pre[0]); int i; for(i=0;i<vin.size();i++) if(pre[0]==vin[i]) break; vector<int> left_pre,left_vin,right_pre,right_vin; for(int j=0;j<i;j++) {left_pre.push_back(pre[j+1]); left_vin.push_back(vin[j]);} for(int j=i+1;j<pre.size();j++) {right_pre.push_back(pre[j]); right_vin.push_back(vin[j]);} p->left=reConstructBinaryTree(left_pre,left_vin); p->right=reConstructBinaryTree(right_pre,right_vin); return p; } };
时间: 2024-10-18 18:18:21