当前位置:网站首页>leetcode 剑指 Offer 28. 对称的二叉树
leetcode 剑指 Offer 28. 对称的二叉树
2022-07-25 10:33:00 【kt1776133839】
题目描述:
请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。
例如,二叉树 [1,2,2,3,4,4,3] 是对称的。
1
/ \
2 2
/ \ / \
3 4 4 3
但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:
1
/ \
2 2
\ \
3 3
样例:
示例 1:
输入:root = [1,2,2,3,4,4,3]
输出:true
示例 2:
输入:root = [1,2,2,null,3,null,3]
输出:false
限制:
0 <= 节点个数 <= 1000
解题思路:
对称二叉树定义: 对于树中 任意两个对称节点 L 和 R ,一定有:
L.val=R.val :即此两对称节点值相等。
L.left.val=R.right.val :即 L 的 左子节点 和 R 的 右子节点 对称;
L.right.val=R.left.val:即 L 的 右子节点 和 R 的 左子节点 对称。
根据以上规律,考虑从顶至底递归,判断每对节点是否对称,从而判断树是否为对称二叉树。

Java程序:
class Solution {
public boolean isSymmetric(TreeNode root) {
return root == null ? true : recur(root.left, root.right);
}
boolean recur(TreeNode L, TreeNode R) {
if(L == null && R == null) return true;
if(L == null || R == null || L.val != R.val) return false;
return recur(L.left, R.right) && recur(L.right, R.left);
}
}
边栏推荐
- 【高并发】通过源码深度分析线程池中Worker线程的执行流程
- Learn NLP with Transformer (Chapter 6)
- HCIP(11)
- 复习背诵整理版
- shell-第五章作业
- Loadbalancerlife lifecycle requested by feign client
- 【flask高级】从源码深入理解flask的应用上下文和请求上下文
- syncronized锁升级的过程
- Signal integrity (SI) power integrity (PI) learning notes (XXXIV) 100 rules of thumb for estimating signal integrity effects
- [树] 100. 相同的树
猜你喜欢

推荐系统-协同过滤在Spark中的实现

HCIA experiment (07) comprehensive experiment

HCIA experiment (06)

Smart cloud IOT platform STM32 esp8266-01s simple wireless light control

What kind of product power does Hongguang miniev, the top seller of new energy, have?

The University of Gottingen proposed clipseg: a model that can perform three segmentation tasks simultaneously using text and image prompts

机智云物联网平台 STM32 ESP8266-01S 简单无线控灯

STM32CubeMX学习记录--安装配置与使用

【IJCAI 2022】参数高效的大模型稀疏训练方法,大幅减少稀疏训练所需资源

Esp8266 uses drv8833 drive board to drive N20 motor
随机推荐
为什么重写equals()方法必须要重写hashCode()方法
Learn NLP with Transformer (Chapter 6)
[dynamic planning] 70. Climbing stairs
Database design - Simplified dictionary table [easy to understand]
Detailed explanation of the implementation method of DNS separation and resolution
MLX90640 红外热成像仪测温模块开发笔记(五)
mysql主从复制与读写分离
Review recitation finishing version
Detailed explanation of lvs-nat and lvs-dr modes of LVS load balancing
HDD Hangzhou station full experience
BGP federal experiment
HCIA experiment (07) comprehensive experiment
Learn PHP -- phpstudy tips mysqld Exe: Error While Setting Value ‘NO_ ENGINE_ Solution of substitution error
让运动自然发生,FITURE打造全新生活方式
[high concurrency] deeply analyze the execution process of worker threads in the thread pool through the source code
The University of Gottingen proposed clipseg: a model that can perform three segmentation tasks simultaneously using text and image prompts
UE4.26源码版学习广域网独立服务器时遇到的客户端运行黑屏问题
HCIP(11)
【高并发】通过源码深度分析线程池中Worker线程的执行流程
Ue4.26 source code version black screen problem of client operation when learning Wan independent server