题解 | #树的子结构#
树的子结构
https://www.nowcoder.com/practice/6e196c44c7004d15b1610b9afca8bd88
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
bool recursion(TreeNode* root1,TreeNode* root2)
{
if(root1==nullptr&&root2!=nullptr)
{
return false;
}
if(root1==nullptr||root2==nullptr)
{
return true;
}
if(root1->val!=root2->val)
return false;
return recursion(root1->left,root2->left)&&recursion(root1->right,root2->right);
}
bool HasSubtree(TreeNode* pRoot1,TreeNode* pRoot2)
{
if(pRoot2==nullptr)
return false;
if(pRoot1==nullptr&&pRoot2!=nullptr)
return false;
if(pRoot1==nullptr||pRoot2==nullptr)
return true;
bool flag1=recursion(pRoot1,pRoot2);
bool flag2=HasSubtree(pRoot1->left,pRoot2);
bool flag3=HasSubtree(pRoot1->right,pRoot2);
return flag1||flag2||flag3;
}
};
学二叉树学的太烂了 大家有好的学习方法或者视频推荐吗
#剑指OFFER#

