码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2019-06-14 12:37:38      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:and   tco   cti   tree   int   init   dict   from   tree node   

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

标签:and   tco   cti   tree   int   init   dict   from   tree node   

原文地址:https://www.cnblogs.com/rosyYY/p/11022424.html

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