剑指 Offer 07. 重建二叉树
题目要求
代码实现
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder)
{
int len = preorder.size();
return build(preorder, inorder,0,len-1,0,len-1);
}
TreeNode* build(vector<int>& preorder, vector<int>& inorder,int f1,int f2,int s1,int s2)
{
int len = f2-f1+1;
if(len == 0)
return NULL;
TreeNode *head = new TreeNode(preorder[f1]);
if(len == 1)
{
return head;
}
int index;
for(int i=s1;i<=s2;i++)
{
if(inorder[i]==preorder[f1])
{
index = i-s1;
break;
}
}
head->left = build(preorder,inorder,f1+1,f1+index,s1,s1+index-1);
head->right = build(preorder,inorder,f1+index+1,f2,s1+index+1,s2);
return head;
}
};
|