leetcode-easy-trees-101. Symmetric Tree-YES

Posted rosyyy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode-easy-trees-101. Symmetric Tree-YES相关的知识,希望对你有一定的参考价值。

mycode   92.44%

# 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 deal(root,level):
            if not root:
                self.res[level].append(None)
                return 0
            self.res[level].append(root.val)  
            deal(root.left,level+1)         
            deal(root.right,level+1)
            
        from collections import defaultdict
        self.res = defaultdict(list) #传入int()函数来初始化
        deal(root,0)
        for level,item in self.res.items():
            if not item == item[::-1]:
                return False
        return True
        
       
            

 

参考

# 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 traver(left,right):
            if not left and not right:
                return True
            if not left or not right:
                return False
            
            return (left.val == right.val) and traver(left.left,right.right) and traver(left.right,right.left)
        
        return traver(root,root)
            

 

以上是关于leetcode-easy-trees-101. Symmetric Tree-YES的主要内容,如果未能解决你的问题,请参考以下文章