검지 offer 문제 4 재건 두 갈래 나무
1143 단어 우객망 프로그래머 면접
, 。
。
{1,2,4,7,3,5,6,8} {4,7,2,1,5,3,8,6}, 。
/**
* 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* construct(vector pre, int ps, int pe, vector vin, int vs, int ve)
{
TreeNode* node = new TreeNode(pre[ps]);
int i;
for(i = vs; vin[i] != node->val; i++);
int l = i - vs;
int r = ve - i;
if(l)
node->left = construct(pre, ps+1, ps+l, vin, vs, vs+l-1);
else
node->left = nullptr;
if(r)
node->right = construct(pre, pe-r+1, pe, vin, ve-r+1, ve);
else
node->right = nullptr;
return node;
}
struct TreeNode* reConstructBinaryTree(vector pre,vector vin)
{
if(pre.size() == 0 || vin.size() == 0 || pre.size() != vin.size())
return nullptr;
return construct(pre, 0, pre.size()-1, vin, 0, vin.size()-1);
}
};