判断二叉树的子结构

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);
    }
};

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值