老卫带你学---leetcode刷题(101. 对称二叉树)

101. 对称二叉树

问题:

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

bash 复制代码
输入:root = [1,2,2,3,4,4,3]
输出:true
bash 复制代码
输入:root = [1,2,2,null,3,null,3]
输出:false
bash 复制代码
提示:

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

解决:

要寻找对称,那只需要递归,然后让左右相等即可

go 复制代码
func isSymmetric(root *TreeNode) bool {
	if root == nil {
		return true
	}
	return dfs(root.Left, root.Right)
}

func dfs(l, r *TreeNode) bool {
	if l == nil && r == nil { //二者都是nil,对称返回true
		return true
	}
	if l == nil || r == nil { //二者有一个为nil,另一个非nil,返回false
		return false
	}
	if l.Val != r.Val {//二者值不同,返回false
		return false
	}
	return dfs(l.Left, r.Right) && dfs(l.Right, r.Left)
}
相关推荐
YGGP28 分钟前
【Golang】LeetCode 128. 最长连续序列
leetcode
月挽清风8 小时前
代码随想录第十五天
数据结构·算法·leetcode
TracyCoder12310 小时前
LeetCode Hot100(34/100)——98. 验证二叉搜索树
算法·leetcode
We་ct12 小时前
LeetCode 56. 合并区间:区间重叠问题的核心解法与代码解析
前端·算法·leetcode·typescript
努力学算法的蒟蒻15 小时前
day79(2.7)——leetcode面试经典150
算法·leetcode·职场和发展
2401_8414956415 小时前
【LeetCode刷题】二叉树的层序遍历
数据结构·python·算法·leetcode·二叉树··队列
2401_8414956415 小时前
【LeetCode刷题】二叉树的直径
数据结构·python·算法·leetcode·二叉树··递归
我是咸鱼不闲呀15 小时前
力扣Hot100系列19(Java)——[动态规划]总结(上)(爬楼梯,杨辉三角,打家劫舍,完全平方数,零钱兑换)
java·leetcode·动态规划
铉铉这波能秀16 小时前
LeetCode Hot100数据结构背景知识之列表(List)Python2026新版
数据结构·leetcode·list
仟濹17 小时前
算法打卡 day1 (2026-02-06 周四) | 算法: DFS | 1_卡码网98 可达路径 | 2_力扣797_所有可能的路径
算法·leetcode·深度优先