码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode&Python] Problem 101. Symmetric Tree

时间:2018-12-30 22:17:03      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:and   amp   type   binary   this   solution   app   check   div   

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

 

 BFS and Iterative:

# 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
        """
        que=[root]
        while que:
            check=[]
            n=len(que)
            for i in range(n):
                node=que.pop(0)
                if node:
                    que.append(node.left)
                    que.append(node.right)
                    check.append(node.val)
                else:
                    check.append(None)
            n=len(check)
            for i in range(n):
                if check[i]!=check[n-i-1]:
                    return False
        return True

  

Recursion:

# 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
        """
        def findsys(node1,node2):
            if node1==None and node2==None:
                return True
            if node1==None or node2==None:
                return False
            return node1.val==node2.val and findsys(node1.left,node2.right) and findsys(node1.right,node2.left)
        
        return findsys(root,root)

  

[LeetCode&Python] Problem 101. Symmetric Tree

标签:and   amp   type   binary   this   solution   app   check   div   

原文地址:https://www.cnblogs.com/chiyeung/p/10200475.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!