题目大意

#!/usr/bin/env python
# coding=utf-8
# Date: 2018-08-30 """
https://leetcode.com/problems/symmetric-tree/description/ 101. Symmetric Tree 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. """ # 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
"""

解题思路

关键点:左子树和右子树成镜像关系,根树与本身成镜像关系。

Approach 1: Recursive 递归法

A tree is symmetric if the left subtree is a mirror reflection of the right subtree.

Therefore, the question is: when are two trees a mirror reflection of each other?

Two trees are a mirror reflection of each other if:

  1. Their two roots have the same value.
  2. The right subtree of each tree is a mirror reflection of the left subtree of the other tree.

This is like a person looking at a mirror. The reflection in the mirror has the same head, but the reflection's right arm corresponds to the actual person's left arm, and vice versa.

The explanation above translates naturally to a recursive function as follows.

Java解法:

public boolean isSymmetric(TreeNode root) {
return isMirror(root, root);
} public boolean isMirror(TreeNode t1, TreeNode t2) {
if (t1 == null && t2 == null) return true;
if (t1 == null || t2 == null) return false;
return (t1.val == t2.val)
&& isMirror(t1.right, t2.left)
&& isMirror(t1.left, t2.right);
}

Python解法:

class Solution(object):
def isSymmetric(self, root):
return self.is_mirror(root, root) def is_mirror(self, t1, t2): # Recursive
if not t1 and not t2:
return True
if not t1 or not t2:
return False
return (t1.val == t2.val) and self.is_mirror(t1.left, t2.right) and self.is_mirror(t1.right, t2.left)

Complexity Analysis

  • Time complexity : O(n)O(n). Because we traverse the entire input tree once, the total run time is O(n)O(n), where nn is the total number of nodes in the tree.
  • Space complexity : The number of recursive calls is bound by the height of the tree. In the worst case, the tree is linear and the height is in O(n)O(n). Therefore, space complexity due to recursive calls on the stack is O(n)O(n) in the worst case.

Approach 2: Iterative 迭代法

Instead of recursion, we can also use iteration with the aid of a queue. Each two consecutive nodes in the queue should be equal, and their subtrees a mirror of each other. Initially, the queue contains root and root. Then the algorithm works similarly to BFS, with some key differences. Each time, two nodes are extracted and their values compared. Then, the right and left children of the two nodes are inserted in the queue in opposite order. The algorithm is done when either the queue is empty, or we detect that the tree is not symmetric (i.e. we pull out two consecutive nodes from the queue that are unequal).

Java解法:

public boolean isSymmetric(TreeNode root) {
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
q.add(root);
while (!q.isEmpty()) {
TreeNode t1 = q.poll();
TreeNode t2 = q.poll();
if (t1 == null && t2 == null) continue;
if (t1 == null || t2 == null) return false;
if (t1.val != t2.val) return false;
q.add(t1.left);
q.add(t2.right);
q.add(t1.right);
q.add(t2.left);
}
return true;
}

Python解法:

class Solution(object):
def isSymmetric(self, root): # Iterative
queue = [root, root]
while queue:
t1, t2 = queue.pop(), queue.pop()
if not t1 and not t2:
continue
if not t1 or not t2 or t1.val != t2.val:
return False
queue.extend([t1.left, t2.right, t1.right, t2.left])
return True

Complexity Analysis

  • Time complexity : O(n)O(n). Because we traverse the entire input tree once, the total run time is O(n)O(n), where nn is the total number of nodes in the tree.
  • Space complexity : There is additional space required for the search queue. In the worst case, we have to insert O(n)O(n) nodes in the queue. Therefore, space complexity is O(n)O(n).

参考:https://leetcode.com/problems/symmetric-tree/solution/

[leetcode] 101. Symmetric Tree 对称树的更多相关文章

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

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

  2. LeetCode 101. Symmetric Tree 判断对称树 C++

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

  3. Leetcode 101 Symmetric Tree 二叉树

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

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

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

  5. 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 对称二叉树(Java & Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 DFS BFS 日期 [LeetCode] 题目地址 ...

  7. LeetCode 101. Symmetric Tree(镜像树)

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

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

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

  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. c/c++值传递和引用传递

    今天看数据结构的时候,因为是c语言版的,刚开始学的时候就对指针搞的焦头烂额,今天,发现参数传递的时候,&符号也莫名其妙,搜了一篇好文,转载下来. 一. 函数参数传递机制的基本理论 函数参数传递 ...

  2. fatal error C1010: unexpected end of file while looking for precompiled header directive

    在编译VS时候,出现fatal error C1010: unexpected end of file while looking for precompiled head. 问题详细解释:致命错误C ...

  3. jQuery中的prop和attr区别

    最近在做一个项目用jq时发现一个问题  在谷歌中可以正常出效果  但是在火狐中就是不行 就是这个prop和attr   之前用的是attr方法   但是在火狐中不出效果  于是特意看了两者的区别 主要 ...

  4. Mac OS 终端下使用 Curl 命令下载文件

    在 mac os下,如何通过命令行来下载网络文件?如果你没有安装或 wget 命令,那么可以使用 curl 工具来达到我们的目的. curl命令参数: curl 'url地址' curl [选项] ' ...

  5. android的hook方面知识点

    android hook分为另种: native层hook---理解ELF文件 java层---虚拟机特性和Java上的反射的作用 注入代码: 存放在哪? 用mmap函数分配临时内存来完成代码存放,对 ...

  6. 20145315 《Java程序设计》第十周学习总结

    20145315 <Java程序设计>第十周学习总结 教材学习内容总结 网络概述 为了能够方便的识别网络上的每个设备,网络中的每个设备都会有一个唯一的数字标识,这个就是IP地址.IP地址实 ...

  7. 20145325张梓靖 《Java程序设计》第2周学习总结

    20145325张梓靖 <Java程序设计>第2周学习总结 教材学习内容总结 整数 short 2字节,int 4字节,long 8字节 字节 byte 1字节 浮点数 float 4字节 ...

  8. Firefox管理已经保存的账号和密码

    https://support.mozilla.org/en-US/kb/password-manager-remember-delete-change-and-import You can easi ...

  9. c#pdf查看器

    Free Spire.PDF for .NET is a Community Edition of the Spire.PDF for .NET, which is a totally free PD ...

  10. Python学习札记(三十) 面向对象编程 Object Oriented Program 1

    参考:OOP NOTE 1.面向对象编程--Object Oriented Programming,简称OOP,是一种程序设计思想.OOP把对象作为程序的基本单元,一个对象包含了数据和操作数据的函数. ...