bool DoFind(Tree *root1,Tree *root2)
{
if(root2 == NULL)//直到找到 要查找的 子树 到了 最底下 为空 说明 此时 一直是正确的
{
return true;
}
if(root1 == NULL)//说明此时 root2并不等于空 (上面两个条件不能写反) (root2 != NULL && root1 == NULL),此时子树 还没有 判断完
{
return false;
}
if(root1->nValue != root2->nValue)
{
return false;
}
return DoFind(root1->pLeft,root2->pLeft) && DoFind(root1->pRight,root2->pRight);
}
bool Find(Tree *root1,Tree *root2)
{
bool flag = false;
if(root1 != NULL && root2 != NULL)
{
if(root1->nValue == root2->nValue)//如果 找到 root1 则从 这里查找 是不是子结构
{
flag = DoFind(root1,root2);
}
if(flag == false)//flag 如果是false 说明还没有找到 子结构 ,还要继续 查找
{
Find(root1->pLeft,root2);
}
if(flag == false)
{
Find(root1->pRight,root2);
}
}
return flag;
}
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSubStructure(TreeNode* A, TreeNode* B) {
if (!A && B) {
return false;
}
if (A && !B) {
return false;
}
if (!A && !B) {
return false;
}
std::queue<TreeNode*> que;
que.push(A);
while (!que.empty()) {
auto f = que.front();
que.pop();
if (f->val == B->val) {
if (dfs(f, B)) {
return true;
}
}
if (f->left) {
que.push(f->left);
}
if (f->right) {
que.push(f->right);
}
}
return false;
}
private:
bool dfs(TreeNode* A, TreeNode* B) {
if (!A && B) {
return false;
}
if (A && !B) {
return true;
}
if (!A && !B) {
return true;
}
if (A->val != B->val) {
return false;
}
return dfs(A->left, B->left) && dfs(A->right, B->right);
}
};