剑指offer 二叉树重建 C++ 牛客网
/**
-
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 pre,vector vin) {
if (pre.empty()||vin.empty())
return nullptr;
TreeNode *root =new TreeNode(pre[0]);
int leftNum=0;
for (int i=0;i<pre.size();++i)
{
if (vin[i]==pre[0])
{
leftNum=i;
break;
}
}
vector preleft,preright,vinleft,vinright;
for (int i=0; i<leftNum;++i)
{
preleft.push_back(pre[i+1]);
vinleft.push_back(vin[i]);
}
for (int i=leftNum+1; i<pre.size();++i)
{
preright.push_back(pre[i]);
vinright.push_back(vin[i]);
}root->left=reConstructBinaryTree(preleft,vinleft); root->right=reConstructBinaryTree(preright,vinright); return root;
}
};