老卫带你学---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)
}
相关推荐
Kuo-Teng20 小时前
LeetCode 160: Intersection of Two Linked Lists
java·算法·leetcode·职场和发展
橘颂TA1 天前
【剑斩OFFER】算法的暴力美学——点名
数据结构·算法·leetcode·c/c++
愚润求学1 天前
【动态规划】专题完结,题单汇总
算法·leetcode·动态规划
·白小白1 天前
力扣(LeetCode) ——43.字符串相乘(C++)
c++·leetcode
一匹电信狗1 天前
【C++11】Lambda表达式+新的类功能
服务器·c++·算法·leetcode·小程序·stl·visual studio
在等晚安么1 天前
力扣面试150题打卡
算法·leetcode·面试
User_芊芊君子1 天前
【LeetCode经典题解】递归破解对称二叉树之谜
算法·leetcode·职场和发展
Rock_yzh1 天前
LeetCode算法刷题——49. 字母异位词分组
数据结构·c++·学习·算法·leetcode·职场和发展·哈希算法
小欣加油1 天前
leetcode 2654 使数组所有元素变成1的最少操作次数
数据结构·c++·算法·leetcode·职场和发展
Kt&Rs1 天前
11.12 LeetCode 题目汇总与解题思路
算法·leetcode