老卫带你学---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)
}
相关推荐
?abc!11 小时前
(数组)581. 最短无序连续子数组
数据结构·算法·leetcode
hold?fish:palm14 小时前
40 二叉树的直径
c++·leetcode
guo_wen_qiang15 小时前
二叉树的层序遍历-使用双端队列Deque
算法·leetcode·1024程序员节
爱读书的小胖15 小时前
LeetCode 55 跳跃游戏 C 语言解题分析
c语言·数据结构·算法·leetcode·1024程序员节
Navigator_Z16 小时前
LeetCode //C - 1300. Sum of Mutated Array Closest to Target
c语言·算法·leetcode
凯瑟琳.奥古斯特17 小时前
力扣1016高效解法:剪枝优化技巧
开发语言·c++·算法·leetcode·职场和发展
qz_Serene18 小时前
练习算法题:双指针 -cpp
c++·算法·leetcode·1024程序员节
Nuanyt19 小时前
Hot 100 刷题笔记 · 数组与哈希专题(3 题)
java·笔记·算法·leetcode·哈希算法·1024程序员节
爱读书的小胖19 小时前
LeetCode 274 H 指数 C 语言解题分析
c语言·算法·leetcode·1024程序员节
如何原谅奋力过但无声1 天前
【LeetCode hot100】代码随想录未cover部分
数据结构·算法·leetcode