代码1和代码2有什么区别,为什么一个对,一个错?
代码1:
classSolution {
public:
boolHasSubtree(TreeNode* pRoot1, TreeNode* pRoot2)
{
if(!pRoot1)
returnfalse;
if(!pRoot2)
returnfalse;
return( dfs(pRoot1,pRoot2)) || HasSubtree(pRoot1->left, pRoot2) || HasSubtree(pRoot1->right, pRoot2);
}
private:
booldfs(TreeNode * r1, TreeNode * r2){
if(!r2)
returntrue;
if(!r1)
returnfalse;
if(r1->val != r2->val)
returnfalse;
returndfs(r1->left, r2->left) && dfs(r1->right, r2->right);
}
};
代码2:
class Solution {
public:
bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2)
{
if(pRoot1==NULL)
return false;
if(pRoot2==NULL)
return false;
return judgesubtree(pRoot1,pRoot2)||HasSubtree(pRoot1->left,pRoot2)||HasSubtree(pRoot1->right,pRoot2);
}
private:
bool judgesubtree(TreeNode* root1, TreeNode* root2)
{
if(root1==NULL)
return false;
if(root2==NULL)
return true;
if(root1->val!=root2->val){
return false;
}
return judgesubtree(root1->left,root2->left)&&judgesubtree(root1->right,root2->right);
}
};
#牛客网在线编程#public:
bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2)
{
if(pRoot1==NULL)
return false;
if(pRoot2==NULL)
return false;
return judgesubtree(pRoot1,pRoot2)||HasSubtree(pRoot1->left,pRoot2)||HasSubtree(pRoot1->right,pRoot2);
}
private:
bool judgesubtree(TreeNode* root1, TreeNode* root2)
{
if(root1==NULL)
return false;
if(root2==NULL)
return true;
if(root1->val!=root2->val){
return false;
}
return judgesubtree(root1->left,root2->left)&&judgesubtree(root1->right,root2->right);
}
};