【LeetCode】101. Symmetric Tree 对称二叉树(Java & Python)
作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/
[LeetCode]
题目地址:https://leetcode.com/problems/symmetric-tree/
Total Accepted: 106639 Total Submissions: 313969 Difficulty: Easy
题目描述
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3] is not:
1
/ \
2 2
\ \
3 3
Note:
- Bonus points if you could solve it both recursively and iteratively.
题目大意
判断一棵二叉树是不是镜像二叉树。
解题方法
DFS
如果一个树是对称的,那么意味着左右子树是镜像的。就像判断回文一样,每层的 左右两边对称位置 的节点是镜像的。
1
/ \
left-> 2 2 <-right
/ \ / \
3 4 4 3
定义新函数isMirror(left, right)
,该函数的意义是判断left
和 right
是不是对称的子树。
- 当
left
和right
的值相等的时候,需要判断下一层是否是对称的。 - 在递归判断下一层的时候的时候,需要判断的是
left.left
和right.right
这两棵树是不是对称的,以及left.right
和right.left
这两棵树是不是对称的。
代码只是上面的思路的实现,可以用递归来完成。递归最重要的是 要明白函数的定义、输入、输出,如果这些没明白一定会把自己绕进去。另外递归的时候应该把递归函数当做黑盒使用,即不需要知道此函数内部怎么实现的,但是调用这个递归函数就是能达到某个功能。这样会帮助理解递归。
本题提醒了我们:在递归的过程中不一定只有一个参数,也可以同时传了两个参数,每次递归的时候同时改变两个采纳数。
Java代码如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isSymmetric(TreeNode root) {
return isMirror(root,root);
}
public boolean isMirror(TreeNode left,TreeNode right){
if(left == null && right == null) return true;
if(left == null || right == null) return false;
return (left.val == right.val) && isMirror(left.left,right.right) && isMirror(left.right,right.left);
}
}
AC:1ms
二刷的时候写的Python解法如下:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root: return True
return self.isMirror(root.left, root.right)
def isMirror(self, left, right):
if not left and not right: return True
if not left or not right: return False
return left.val == right.val and self.isMirror(left.left, right.right) and self.isMirror(left.right, right.left)
BFS
BFS 使用一个队列,把要判断是否为镜像的节点放在一起。
在队列中同时取出两个节点left, right
,判断这两个节点的值是否相等,然后把他们的孩子中按照(left.left, right.right)
一组,(left.right, right.left)
一组放入队列中。
BFS做法需要把所有的节点都检查完才能确定返回结果True
,除非提前遇到不同的节点值而终止返回False
。
Java代码如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isSymmetric(TreeNode root) {
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
q.add(root);
while(!q.isEmpty()){
TreeNode left=q.poll();
TreeNode right=q.poll();
if(left==null && right==null) continue;
if(left==null || right==null) return false;
if(left.val != right.val) return false;
q.add(left.left);
q.add(right.right);
q.add(left.right);
q.add(right.left);
}
return true;
}
}
AC:3ms
二刷的时候的Python解法如下:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root: return True
que = collections.deque()
que.append(root.left)
que.append(root.right)
while que:
left, right = que.popleft(), que.popleft()
if not left and not right:
continue
if not left or not right:
return False
if left.val != right.val:
return False
que.append(left.left)
que.append(right.right)
que.append(left.right)
que.append(right.left)
return True
一种便于理解的BFS做法,把要判断的是否对称节点作为tuple一起放入队列中:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
queue = collections.deque()
queue.append((root, root))
while queue:
left, right = queue.popleft()
if not left and not right:
continue
if not left or not right:
return False
if left.val != right.val:
return False
queue.append((left.left, right.right))
queue.append((left.right, right.left))
return True
日期
2016 年 05月 8日
2018 年 11 月 19 日 —— 周一又开始了
2020 年 5 月 31 日 —— 准备组织每日一题的分享
【LeetCode】101. Symmetric Tree 对称二叉树(Java & Python)的更多相关文章
- [leetcode] 101. Symmetric Tree 对称树
题目大意 #!/usr/bin/env python # coding=utf-8 # Date: 2018-08-30 """ https://leetcode.com ...
- 【LeetCode】Symmetric Tree(对称二叉树)
这道题是LeetCode里的第101道题.是我在学数据结构——二叉树的时候碰见的题. 题目如下: 给定一个二叉树,检查它是否是镜像对称的. 例如,二叉树 [1,2,2,3,4,4,3] 是对称的. 1 ...
- [leetcode]101. Symmetric Tree对称树
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). For e ...
- Leetcode 101 Symmetric Tree 二叉树
判断一棵树是否自对称 可以回忆我们做过的Leetcode 100 Same Tree 二叉树和Leetcode 226 Invert Binary Tree 二叉树 先可以将左子树进行Invert B ...
- (二叉树 DFS 递归) leetcode 101. Symmetric Tree
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). For e ...
- LeetCode 101. Symmetric Tree (对称树)
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). For e ...
- [Leetcode] Symmetric tree 对称二叉树
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). For e ...
- Java for LeetCode 101 Symmetric Tree
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). For e ...
- leetcode 101 Symmetric Tree ----- java
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). For e ...
随机推荐
- FASTA/Q序列处理神器---seqkit
该软件对于处理FASTA/Q十分方便,省去自己编写脚本 安装 1 conda install seqkit 使用 序列操作(seq) 1 ## 取方向序列 2 seqkit seq test.fa - ...
- 毕业设计之zabbix+微信企业号报警
需要自己申请一个微信企业号 创建应用 AgentId 1000003 Secret SOI8b20G96yUVM29K02-bP5N5o6dovwSF2RrDaXHJNg 企业ID(自己再企业信息里面 ...
- 2.MaxSubArray-Leetcode
题目:最大连续子序列和 思路:动态规划 状态转移方程 f[j]=max{f[j-1]+s[j],s[j]}, 其中1<=j<=n target = max{f[j]}, 其中1<=j ...
- MybatisPlus入门程序
参考资料:MybatisPlus官网 环境搭建 创建数据库 CREATE DATABASE `mybatisplus` USE `mybatisplus` CREATE TABLE `user ...
- 前端2 — CSS — 更新完毕
1.CSS是什么? 指:Cascading Style Sheet --- 层叠样式表 CSS 即:美化网页( 在HTML不是说过W3C规定网页为三种标准嘛,结构层HTML已经玩了,而这个CSS就是 ...
- python生成器浅析
A 'generator' is a function which returns a generator iterator. It looks like a normal function exce ...
- 大数据学习day26----hive01----1hive的简介 2 hive的安装(hive的两种连接方式,后台启动,标准输出,错误输出)3. 数据库的基本操作 4. 建表(内部表和外部表的创建以及应用场景,数据导入,学生、分数sql练习)5.分区表 6加载数据的方式
1. hive的简介(具体见文档) Hive是分析处理结构化数据的工具 本质:将hive sql转化成MapReduce程序或者spark程序 Hive处理的数据一般存储在HDFS上,其分析数据底 ...
- Vue相关,vue父子组件生命周期执行顺序。
一.实例代码 父组件: <template> <div id="parent"> <child></child> </div& ...
- Nested Classes in C++
A nested class is a class which is declared in another enclosing class. A nested class is a member a ...
- Linux学习 - 挂载命令
一.mount 1 功能 将外设手工挂载到目标挂载点 2 语法 mount [-t 文件系统] [设备文件名] [挂载点] 3 范例 mkdir /mnt/cdrom 在/mnt下创建一个cd ...