题目描述
输入两棵二叉树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 (!pRoot2) return false;
if (!pRoot1) return false;
return (dfs(pRoot1,pRoot2) || HasSubtree(pRoot1->left,pRoot2) || HasSubtree(pRoot1->right,pRoot2));
}
private:
bool dfs(TreeNode* pRoot1, TreeNode* pRoot2)
{
if (!pRoot2) return true;
if (!pRoot1) return false;
if (pRoot1->val == pRoot2->val) return (dfs(pRoot1->left,pRoot2->left)&&dfs(pRoot1->right,pRoot2->right));
return false;
}
};
class IdenticalTree {
public:
bool isSame(TreeNode* A, TreeNode* B)
{
if(A==NULL && B==NULL)return true;
else if(A==NULL || B==NULL) return false;
else
return (A->val == B->val) && isSame(A->left,B->left) && isSame(A->right,B->right);
}
bool chkIdentical(TreeNode* A, TreeNode* B) {
if(A==NULL&&B==NULL)
return true;
else if(A==NULL||B==NULL)
return false;
else if(isSame(A,B))
return true;
else
return chkIdentical(A->left,B)||chkIdentical(A->right,B);
}
};