当前位置:网站首页>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);
}
}
边栏推荐
- Shell Chapter 5 homework
- Some usages of beautifulsoup
- Nowcodertop7-11 - continuous updating
- Hcip experiment (04)
- SQL语言(四)
- Learn Luzhi PHP -- tp5.0 uses Chinese as an alias and reports "unsupported data expression"
- C# Newtonsoft.Json 高级用法
- [flask advanced] deeply understand the application context and request context of flask from the source code
- NowCoderTOP1-6——持续更新ing
- Reinforcement Learning 强化学习(四)
猜你喜欢

学习路之PHP--TP5.0使用中文当别名,报“不支持的数据表达式”

游戏背包系统,“Inventory Pro插件”,研究学习-----妈妈再也不用担心我不会做背包了(Unity3D)

PostgreSQL踩坑 | ERROR: operator does not exist: uuid = character varying

HCIA experiment (09)
Learn NLP with Transformer (Chapter 2)

复习背诵整理版

Hcip experiment (04)

B2B2C多商户系统功能丰富,极易二开!!!

C# Newtonsoft. Jason advanced usage
Details of the list of state products that Apple announced to be eligible for the sales tax holiday in the United States
随机推荐
Learn NLP with Transformer (Chapter 2)
TPS calculation in performance test [Hangzhou multi tester] [Hangzhou multi tester _ Wang Sir]
shell-第四天作业
新能源销冠宏光MINIEV,有着怎样的产品力?
Learn NLP with Transformer (Chapter 7)
There is a newline problem when passing shell script parameters \r
HCIA experiment (06)
【IJCAI 2022】参数高效的大模型稀疏训练方法,大幅减少稀疏训练所需资源
Getting started with redis
游戏背包系统,“Inventory Pro插件”,研究学习-----妈妈再也不用担心我不会做背包了(Unity3D)
Syncronized lock upgrade process
Mlx90640 infrared thermal imager temperature measurement module development notes (V)
mysql高级语句(一)(总有一个人的出现,让你的生活不再继续糟糕)
Loadbalancerlife lifecycle requested by feign client
LVS load balancing lvs-dr builds Web Clusters and LVS combines with kept to build highly available Web Clusters
Learn NLP with Transformer (Chapter 1)
SQL语言(一)
Ue4.26 source code version black screen problem of client operation when learning Wan independent server
How can you use unity without several plug-ins? Unity various plug-ins and tutorial recommendations
[flask advanced] deeply understand the application context and request context of flask from the source code