描述
输入两棵二叉树A,B,判断B是不是A的子结构。(我们约定空树不是任意一个树的子结构)
假如给定A为{8,8,7,9,2,#,#,#,#,4,7},B为{8,9,2},2个树的结构如下,可以看出B是A的子结构
数据范围:
0 <= A的节点个数 <= 10000
0 <= B的节点个数 <= 10000
示例1
{8,8,7,9,2,#,#,#,#,4,7},{8,9,2}
true
示例2
{1,2,3,4,5},{2,4}
true
代码
/*
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 == NULL || pRoot2 == NULL) {
return false;
}
return subtree(pRoot1, pRoot2) || HasSubtree(pRoot1->left, pRoot2) ||
HasSubtree(pRoot1->right, pRoot2);
}
bool subtree(TreeNode* pRoot1, TreeNode* pRoot2) {
if (pRoot2 == NULL) {
return true;
}
if (pRoot1 == NULL) {
return false;
}
if (pRoot1->val != pRoot2->val) {
return false;
}
return subtree(pRoot1->left, pRoot2->left) &&
subtree(pRoot1->right, pRoot2->right);
}
};