Leetcode 101. 对称二叉树 递归和迭代。

题目

在这里插入图片描述

递归

递归的思想首先判断是哪种遍历方式,这道题应该是前序遍历,因为要从根节点开始,那么依次判断根的左节点和右节点是否相等。

  1. 前序遍历
  2. 递归的结构 dfs(root1->left,root2->right), dfs(root1->right,root2->left)
  3. 递归结束的条件
class Solution {
public:
    bool isSymmetric(TreeNode* root) {
        if(root == NULL)
            return true;
        bool res = func(root,root);
        return res;
    }
    
    bool func(TreeNode* root1,TreeNode* root2)
    {
        if(root1 == NULL && root2 == NULL)
            return true;
        if(root1==NULL || root2==NULL)
            return false;
        if(root1->val != root2->val)
            return false;
        bool left = func(root1->left,root2->right);
        bool right = func(root1->right,root2->left);
        
        return left&&right;
    }
};

迭代

迭代我们可以使用bfs的方式,层序遍历对于每一层我们调用判断回文的函数。从而可以实现迭代的方法。

另一种迭代方式我们可以两两入队,出队保证比较的元素刚好是对称位置上的,如下代码所示:

class Solution {
public:
     bool isSymmetric(TreeNode* root) {
        if (root == NULL) {
            return true;
        }
        
        queue<TreeNode*> queue;
        queue.push(root->left);
        queue.push(root->right);

        while (!queue.empty()) {
            TreeNode* node1 = queue.front();
            queue.pop();
            TreeNode* node2 = queue.front();
            queue.pop();
            if (node1 == NULL && node2 == NULL) {
                continue;
            }
            if (node1 == NULL || node2 == NULL || node1->val != node2->val) {
                return false;
            }
            queue.push(node1->left);
            queue.push(node2->right);
            queue.push(node1->right);
            queue.push(node2->left);
        }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值