作者: 负雪明烛
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:

  1. Bonus points if you could solve it both recursively and iteratively.

题目大意

判断一棵二叉树是不是镜像二叉树。

解题方法

DFS

如果一个树是对称的,那么意味着左右子树是镜像的。就像判断回文一样,每层的 左右两边对称位置 的节点是镜像的。

		     1
/ \
left-> 2 2 <-right
/ \ / \
3 4 4 3

定义新函数isMirror(left, right),该函数的意义是判断leftright是不是对称的子树。

  1. leftright的值相等的时候,需要判断下一层是否是对称的。
  2. 在递归判断下一层的时候的时候,需要判断的是 left.leftright.right这两棵树是不是对称的,以及 left.rightright.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)的更多相关文章

  1. [leetcode] 101. Symmetric Tree 对称树

    题目大意 #!/usr/bin/env python # coding=utf-8 # Date: 2018-08-30 """ https://leetcode.com ...

  2. 【LeetCode】Symmetric Tree(对称二叉树)

    这道题是LeetCode里的第101道题.是我在学数据结构——二叉树的时候碰见的题. 题目如下: 给定一个二叉树,检查它是否是镜像对称的. 例如,二叉树 [1,2,2,3,4,4,3] 是对称的. 1 ...

  3. [leetcode]101. Symmetric Tree对称树

    Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). For e ...

  4. Leetcode 101 Symmetric Tree 二叉树

    判断一棵树是否自对称 可以回忆我们做过的Leetcode 100 Same Tree 二叉树和Leetcode 226 Invert Binary Tree 二叉树 先可以将左子树进行Invert B ...

  5. (二叉树 DFS 递归) leetcode 101. Symmetric Tree

    Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). For e ...

  6. LeetCode 101. Symmetric Tree (对称树)

    Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). For e ...

  7. [Leetcode] Symmetric tree 对称二叉树

    Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). For e ...

  8. 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 ...

  9. leetcode 101 Symmetric Tree ----- java

    Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). For e ...

随机推荐

  1. R 语言实战-Part 4 笔记

    R 语言实战(第二版) part 4 高级方法 -------------第13章 广义线性模型------------------ #前面分析了线性模型中的回归和方差分析,前提都是假设因变量服从正态 ...

  2. fastq文件基本信息统计工具

    之前写的一个小工具,写的很简陋,名字取的也很随意就叫skr,哈哈.主要是fq转fa.合并多个染色体的vcf文件等,功能不多(主要是C写起来太操蛋了T_T),通常我也只用来统计fastq文件信息: 这里 ...

  3. javaSE高级篇1 — 异常与多线程基础

    1.异常的体系结构  注:Throwable是一个类,不是一个接口,这个类里面是描述的一些Error和Exception的共性,如图所示: 异常 / 错误是什么意思? 定义:指的是程序运行过程中,可能 ...

  4. python写的多项式符号乘法

    D:\>poly.py(x - 1) * (x^2 + x + 1) = x^3 - 1 1 import ply.lex as lex # pip install ply 2 import p ...

  5. abuse

    abuse 近/反义词: ill-treat, maltreat, mistreat, misuse, prostitute, spoil; defame, disparage, malign, re ...

  6. 【leetcode】378. Kth Smallest Element in a Sorted Matrix(TOP k 问题)

    Given an n x n matrix where each of the rows and columns is sorted in ascending order, return the kt ...

  7. 给webapp加上一个apk外壳

    原文:http://blog.csdn.net/cmyh100/article/details/77862962 1.在Android Studio里创建一个项目 2.创建MyApplication. ...

  8. 【Git项目管理】git新手入门——基础教程

    一.Git工作流程 直接上手看图,了解Git工具的工作流程: 以上包括一些简单而常用的命令,但是先不关心这些,先来了解下面这4个专有名词. Workspace:工作区 Index / Stage:暂存 ...

  9. c学习 - 第七章:数组

    7.3.6 字符串处理函数 (1).puts(字符数组) 字符串输出到终端 (2).gets(字符数组) 从标准输入获取字符串(包括空格) (3).strcat(字符数组1,字符数组2) 连接两个字符 ...

  10. JDBC(1):JDBC介绍

    一,JDBC介绍 SUN公司为了简化.统一对数据库的操作,定义了一套Java操作数据库的规范(接口),称之为JDBC.这套接口由数据库厂商去实现,这样,开发人员只需要学习jdbc接口,并通过jdbc加 ...