老卫带你学---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)
}
相关推荐
CoderYanger1 小时前
动态规划算法-子序列问题(数组中不连续的一段):28.摆动序列
java·算法·leetcode·动态规划·1024程序员节
有时间要学习2 小时前
面试150——第二周
数据结构·算法·leetcode
小白程序员成长日记5 小时前
2025.12.03 力扣每日一题
算法·leetcode·职场和发展
元亓亓亓5 小时前
LeetCode热题100--20. 有效的括号--简单
linux·算法·leetcode
熊猫_豆豆5 小时前
LeetCode 49.字母异位组合 C++解法
数据结构·算法·leetcode
小武~7 小时前
Leetcode 每日一题C 语言版 -- 234 basic calculator
linux·c语言·leetcode
小白程序员成长日记7 小时前
2025.12.02 力扣每日一题
数据结构·算法·leetcode
吃着火锅x唱着歌8 小时前
LeetCode 3583.统计特殊三元组
算法·leetcode·职场和发展
狐578 小时前
2025-12-04-LeetCode刷题笔记-2211-统计道路上的碰撞次数
笔记·算法·leetcode
小南家的青蛙9 小时前
LeetCode第773题 - 滑动谜题
算法·leetcode·职场和发展