leetcode_101. 对称二叉树

举报
悲恋花丶无心之人 发表于 2021/02/02 23:49:44 2021/02/02
【摘要】 目录 一、题目内容 二、解题思路 三、代码 一、题目内容 给定一个二叉树,检查它是否是镜像对称的。 例如,二叉树 [1,2,2,3,4,4,3] 是对称的。     1    / \   2   2  / \ / \ 3  4 4  3 &nb...

目录

一、题目内容

二、解题思路

三、代码


一、题目内容

给定一个二叉树,检查它是否是镜像对称的。

例如,二叉树 [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

 

进阶:

你可以运用递归和迭代两种方法解决这个问题吗?

二、解题思路

从根节点往下开始判断相应子树的对称位置是否相等即可

三、代码


      class Solution:
      def isSymmetric(self, root: TreeNode) -> bool:
      if root is None:
      return True
      if root is not None and root.left is None and root.right is None:
      return True
      def dfs(left, right):
      if left is not None and right is not None:
      if left.val == right.val:
      if dfs(left.left, right.right) is False:
      return False
      if dfs(left.right, right.left) is False:
      return False
      return True
      else:
      return False
      elif left is None and right is not None:
      return False
      elif left is not None and right is None:
      return False
      return dfs(root.left, root.right)
  
 

文章来源: nickhuang1996.blog.csdn.net,作者:悲恋花丶无心之人,版权归原作者所有,如需转载,请联系作者。

原文链接:nickhuang1996.blog.csdn.net/article/details/108706398

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。