LeetCode--101. 对称二叉树(二叉树)

题目描述

给你一个二叉树的根节点 root , 检查它是否轴对称。

示例 1:

复制代码
输入:root = [1,2,2,3,4,4,3]
输出:true

示例 2:

复制代码
输入:root = [1,2,2,null,3,null,3]
输出:false

提示:

  • 树中节点数目在范围 [1, 1000]
  • -100 <= Node.val <= 100

**进阶:**你可以运用递归和迭代两种方法解决这个问题吗?

代码

使用递归法:

java 复制代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    
    public boolean isSame(TreeNode left, TreeNode right){
        if(left == null || right == null) return left==right;
        // 这一层的左右 && 下一层的外侧 && 下一层的里侧
        return left.val == right.val && isSame(left.left, right.right) && isSame(left.right, right.left);
    }
    
    public boolean isSymmetric(TreeNode root) {
        // 使用递归法
        if(root == null) return true;
        return isSame(root.left, root.right);
    }
}

借助列表,层序遍历:

java 复制代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean isSymmetric(TreeNode root) {
        List<TreeNode> que = new LinkedList<>();
        if(root.left == null && root.right == null) return true;
        que.add(root);
        while(!que.isEmpty()){
            int size = que.size();
            // 先做比较
            for(int i=0; i<size/2; i++){
                TreeNode pre = que.get(i);
                TreeNode last = que.get(size-i-1);
                if(pre == last) continue;
                if(pre == null || last == null || pre.val != last.val) return false;
            }
            // 再新增子节点 null也要
            for(int i=0; i<size; i++){
                TreeNode node = que.remove(0);
                if(node != null){
                    que.add(node.left);
                    que.add(node.right);
                }
                
            }
        }
        return true;
    }
}
相关推荐
To_OC12 小时前
LC 994 腐烂的橘子:人人都说是 BFS 入门题,我却写了三遍才过
javascript·算法·leetcode
金銀銅鐵15 小时前
[Python] 扩展欧几里得算法
python·数学·算法
To_OC18 小时前
LC 200 岛屿数量:经典 DFS 入门题,我第一次写居然连方向都搞错了
javascript·算法·leetcode
To_OC1 天前
LC 128 最长连续序列:别上来就排序,O (n) 解法才是这题的灵魂
javascript·算法·leetcode
05Kevin2 天前
lk每日冒险题--数据结构6.27
算法
To_OC2 天前
从一次栈溢出报错说起,我把递归彻底扒明白了
javascript·算法·程序员
千纸鹤安安3 天前
千问Qwen-AgentWorld来了:一个语言模型搞定七大Agent场景,GPT-5.4都输了
算法
七牛开发者3 天前
MCP 到底是什么?为什么 Agent 都想接上它
算法·aigc·agent