LeetCode-101-Symmetric Tree-E(DFS BFS)

本文介绍了一种检查二叉树是否为中心对称的方法,提供了两种实现方式:递归解法(深度优先搜索DFS)和迭代解法(广度优先搜索BFS)。递归解法通过比较左右子树来判断是否对称,而迭代解法则使用队列来逐层进行比较。

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

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
这里写图片描述

Note:

  • Bonus points if you could solve it both recursively and iteratively.

递归解法(DFS):

bool isSymmetric(TreeNode* root) {
        if(root==NULL)
            return true;
        return isMirror(root->left,root->right);
}

bool isMirror(TreeNode* root1,TreeNode* root2){
        if(root1==NULL && root2==NULL)
            return true;
        if(root1==NULL || root2==NULL)
            return false;
        return (root1->val==root2->val && isMirror(root1->left,root2->right) && 
               isMirror(root1->right,root2->left));    

}

迭代解法(BFS):

bool isSymmetric(TreeNode* root) {
        if(!root)
            return true;
        TreeNode*l = root->left;
        TreeNode*r = root->right;

        queue<TreeNode*>left;
        queue<TreeNode*>right;

        left.push(l);
        right.push(r);

        while(!left.empty()&&!right.empty()){      
            l=left.front();
            r=right.front();
            left.pop();
            right.pop();
            if(l==NULL&&r==NULL)
                continue;
            if(l==NULL||r==NULL)
                return false;
            if(l->val!=r->val)
                return false;
            left.push(l->left);
            left.push(l->right);
            right.push(r->right);
            right.push(r->left);
        }
        return true;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值