前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Q101 Symmetric Tree

Q101 Symmetric Tree

作者头像
echobingo
发布2018-04-25 16:48:03
4950
发布2018-04-25 16:48:03
举报

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

代码语言:javascript
复制
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.
解题思路:

简单方法,就是复制一棵相同的数,然后比较左右结点是否满足对称树的条件。由于原函数只传入了一棵树的根节点,因此需要重新定义一个函数,可以传入两棵树的根节点,然后进行比较。

Python实现:
代码语言:javascript
复制
# 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):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if root == None:
            return True
        return Solution.isMirror(self, root.left, root.right)
        

    def isMirror(self, p, q):
        if p == None and q == None: 
            return True
        if p != None and q != None and p.val == q.val:
            return Solution.isMirror(self, p.left, q.right) and Solution.isMirror(self, p.right, q.left)
        else:
            return False
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.02.28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 解题思路:
  • Python实现:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档