当前位置:网站首页>二叉树——101. 对称二叉树
二叉树——101. 对称二叉树
2022-07-25 23:55:00 【向着百万年薪努力的小赵】
1 题目描述
给你一个二叉树的根节点 root , 检查它是否轴对称。
2 题目示例


3 题目提示
树中节点数目在范围 [1, 1000] 内
-100 <= Node.val <= 100
4 思路
递归:
如果一个树的左子树与右子树镜像对称,那么这个树是对称的。
因此,该问题可以转化为:两个树在什么情况下互为镜像?
如果同时满足下面的条件,两个树互为镜像:
- 它们的两个根结点具有相同的值
- 每个树的右子树都与另一个树的左子树镜像对称
我们可以实现这样一个递归函数,通过「同步移动」两个指针的方法来遍历这棵树,p指针和q指针—开始都指向这棵树的根,随后p右移时,q左移,p左移时,q右移。每次检查当前p和q节点的值是否相等,如果相等再判断左右子树是否对称。
复杂度分析
假设树上—共n个节点。
时间复杂度:这里遍历了这棵树,渐进时间复杂度为O(n)
·空间复杂度:这里的空间复杂度和递归使用的栈空间有关,这里递归层数不超过n,故渐进空间复杂度为O(n)。
迭代:
「方法—」中我们用递归的方法实现了对称性的判断,那么如何用迭代的方法实现呢?首先我们引入一个队列,这是把递归程序改写成迭代程序的常用方法。初始化时我们把根节点入队两次。每次提取两个结点并比较它们的值(队列中每两个连续的结点应该是相等的,而且它们的子树互为镜像),然后将两个结点的左右子结点按相反的顺序插入队列中。当队列为空时,或者我们检测到树不对称(即从队列中取出两个不相等的连续结点)时,该算法结束。
复杂度分析
· 时间复杂度:O(n),同「方法一」。
· 空间复杂度:这里需要用一个队列来维护节点,每个节点最多进队—次,出队一次,队列中最多不会超过n个点,故渐进空间复杂度为O(n)。
5 我的答案
递归:
class Solution {
public boolean isSymmetric(TreeNode root) {
return check(root, root);
}
public boolean check(TreeNode p, TreeNode q) {
if (p == null && q == null) {
return true;
}
if (p == null || q == null) {
return false;
}
return p.val == q.val && check(p.left, q.right) && check(p.right, q.left);
}
}
迭代:
class Solution {
public boolean isSymmetric(TreeNode root) {
return check(root, root);
}
public boolean check(TreeNode u, TreeNode v) {
Queue<TreeNode> q = new LinkedList<TreeNode>();
q.offer(u);
q.offer(v);
while (!q.isEmpty()) {
u = q.poll();
v = q.poll();
if (u == null && v == null) {
continue;
}
if ((u == null || v == null) || (u.val != v.val)) {
return false;
}
q.offer(u.left);
q.offer(v.right);
q.offer(u.right);
q.offer(v.left);
}
return true;
}
}
边栏推荐
- Storage of data in memory
- Good news under the epidemic
- 二叉树——530.二叉搜索树的最小绝对差
- [ManageEngine] servicedesk plus won the 2022 safety model engineering data safety award
- Nacos 下线服务时报错 errCode: 500
- LeetCode 0136. 只出现一次的数字:异或
- TOPSIS and entropy weight method
- Typescript TS basic knowledge and so on
- LeetCode 0919. 完全二叉树插入器:完全二叉树的数组表示
- SQLZOO——Nobel Quiz
猜你喜欢
随机推荐
程序环境和预处理
redis-基本数据类型(String/list/Set/Hash/Zset)
Qt智能指针易错点
Call nailing API and report an error: the signature sent by the robot is expired; Solution: please keep the signature generation time and sending time within timestampms
152. Product maximum subarray - dynamic programming
[Muduo] package EventLoop and thread
你还在用浏览器自带书签?这款书签插件超赞
Macro task, micro task and event cycle mechanism
ShardingSphere数据分片
R语言安装教程 | 图文介绍超详细
二叉树——530.二叉搜索树的最小绝对差
How to solve cross domain problems
[ManageEngine] servicedesk plus won the 2022 safety model engineering data safety award
arcgis根据矢量范围裁取tif影像(栅格数据)、批量合并shp文件、根据矢量范围裁取区域内的矢量,输出地理坐标系、转换16位TIF影像的像素深度至8位、shp文件创建和矢量框标绘设置
Payment terms in SAP message No. vg202 IDoc e1edk18 have been transferred: check data
S4/HANA MM & SD EDI基于NAST的集成配置(ORDERS, ORDRSP, DESADV, INVOIC)
Numerical learning iota, accumulate
行为型模式之责任链模式
R language installation tutorial | graphic introduction is super detailed
SAP Message No. VG202 IDoc E1EDK18 中付款条款已经转移:检查数据









