[LeetCode&Python] Problem 101. Symmetric Tree

Posted chiyeung

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode&Python] Problem 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

 

 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的主要内容,如果未能解决你的问题,请参考以下文章

C++&Python描述 LeetCode C++&Python描述 LeetCode 剑指 Offer 22. 链表中倒数第k个节点

[LeetCode&Python] Problem 202. Happy Number

[LeetCode&Python] Problem 520. Detect Capital

[LeetCode&Python] Problem 383. Ransom Note

[LeetCode&Python] Problem 458. Poor Pigs

[LeetCode&Python] Problem 682. Baseball Game