/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
struct TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> in) {
if(pre.size() == 0)
return NULL;
TreeNode * p = (TreeNode *)malloc(sizeof(TreeNode));
p->val = pre[0];
int i = 0, j;
for(; i < in.size(); i++)
{
if(pre[0] == in[i])
break;
}
vector<int> rpre, rin, lpre, lin;
for(j = 1; j < i + 1; j++)
lpre.push_back(pre[j]);
for(j = i + 1; j < pre.size(); j++)
rpre.push_back(pre[j]);
for(j = 0; j < i; j++)
lin.push_back(in[j]);
for(j = i + 1; j < in.size(); j++)
rin.push_back(in[j]);
p->left = reConstructBinaryTree(lpre, lin);
p->right = reConstructBinaryTree(rpre, rin);
return p;
}
};
剑指offer之重建二叉树
最新推荐文章于 2020-04-07 20:52:07 发布