题目描述
输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
题解
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2) {
if(pRoot1 == nullptr || pRoot2 == nullptr)
return false;
return isSubtree(pRoot1, pRoot2) ||
isSubtree(pRoot1->left, pRoot2) ||
isSubtree(pRoot1->right, pRoot2);
}
bool isSubtree(TreeNode* t1, TreeNode* t2) {
if(t2 == nullptr)
return true;
if(t1 == nullptr)
return false;
if(t1->val == t2->val) {
return isSubtree(t1->left, t2->left) &&
isSubtree(t1->right, t2->right);
}
return false;
}
};