老卫带你学---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)
}
相关推荐
2351620 小时前
【LeetCode】146. LRU 缓存
java·后端·算法·leetcode·链表·缓存·职场和发展
tkevinjd1 天前
反转链表及其应用(力扣2130)
数据结构·leetcode·链表
程序员烧烤1 天前
【leetcode刷题007】leetcode116、117
算法·leetcode
Swift社区1 天前
LeetCode 395 - 至少有 K 个重复字符的最长子串
算法·leetcode·职场和发展
Espresso Macchiato1 天前
Leetcode 3710. Maximum Partition Factor
leetcode·职场和发展·广度优先遍历·二分法·leetcode hard·leetcode 3710·leetcode双周赛167
巴里巴气1 天前
第15题 三数之和
数据结构·算法·leetcode
西阳未落1 天前
LeetCode——双指针(进阶)
c++·算法·leetcode
熬了夜的程序员1 天前
【LeetCode】69. x 的平方根
开发语言·算法·leetcode·职场和发展·动态规划
Swift社区2 天前
LeetCode 394. 字符串解码(Decode String)
算法·leetcode·职场和发展
tt5555555555552 天前
LeetCode进阶算法题解详解
算法·leetcode·职场和发展