剑指27 二叉树的镜像 28.对称的二叉树 26.树的子结构

文章介绍了两种方法来检查二叉树的对称性:一种是使用队列的迭代方法,另一种是递归方法。在迭代中,通过广度优先搜索交换节点的左右子树;递归方法则直接交换根节点的左右子树并递归处理子树。此外,还提供了验证子结构是否相同的辅助函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述
方法1:队列迭代
方法2:递归
队列迭代:

class Solution {
public:
    TreeNode* mirrorTree(TreeNode* root) {
        queue<TreeNode*> q;
        if(root==NULL) return root;
        q.push(root);
        while(!q.empty())
        {
            TreeNode *cur=q.front();
            if(!cur) continue;//不要忘记谢谢
            swap(cur->left,cur->right);
            q.pop();
            if(cur->left) q.push(cur->left);
            if(cur->right) q.push(cur->right);
        }
        return root;
    }
};

递归

class Solution {
public:
    TreeNode* mirrorTree(TreeNode* root) {
        queue<TreeNode*> q;
        if(root==NULL) return root;
        swap(root->left,root->right);
        mirrorTree(root->left);
        mirrorTree(root->right);
        return root;
    }
};

在这里插入图片描述
基于上面的基础,我看看对称后的树是不是和当前树一样
先递归

class Solution {
public:
    bool DFSSymmetric(TreeNode* A,TreeNode* B)
    {
        if(!A&&!B) return true;
        else if(A&&B)
        {
            return (A->val==B->val)&&DFSSymmetric(A->left,B->right)&&(DFSSymmetric(A->right,B->left));}
        else return false;
    }
    bool isSymmetric(TreeNode* root)
    {
        if(root==NULL) return true;
        return DFSSymmetric(root->left,root->right);
    }
};

队列迭代

class Solution {
public:
    bool Symmetric(TreeNode* A,TreeNode* B)
    {
        queue<TreeNode*> q;
        q.push(A),q.push(B);
        while(!q.empty())
        {
            TreeNode *a=q.front();
            q.pop();
            TreeNode *b=q.front();
            q.pop();
           if (!a && !b) continue;
            if ((!a || !b) || (a->val != b->val)) return false;
            q.push(a->left); //前面已经判断完a b为空的情况 到这边a,b肯定不为空,至于左孩子右孩子最不济也是null
            q.push(b->right);
            q.push(a->right); 
            q.push(b->left)}
        return 1;
    }
    bool isSymmetric(TreeNode* root)
    {
        if(root==NULL) return true;
        return Symmetric(root->left,root->right);
    }
};

在这里插入图片描述
递归 注意边界条件

class Solution {
public:
    bool SubStructure(TreeNode* A, TreeNode* B)
    {
        if(!B) return 1;//结束条件1,B最后一个遍历完了
        if(!A||A->val!=B->val) return 0;
        return SubStructure(A->left,B->left)&&SubStructure(A->right,B->right);
    }
    bool isSubStructure(TreeNode* A, TreeNode* B) {
        if(!A||!B) return 0;//其中一个存在
        // 根节点相同直接比较,根节点不同看B是不是A的左右子树结构
        return SubStructure(A,B)||isSubStructure(A->left,B)||isSubStructure(A->right,B);
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值