python - symmetric tree


  • 0
    S
    # 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
            """
    
            if root:
                queue, depth = [(root, 0)], 0
                while queue:
                    # 1. enqueue the children in the next level
                    tmpq = []
                    for node, pos in queue:
                        if node.left: tmpq.append((node.left, pos*2))
                        if node.right: tmpq.append((node.right, pos*2 +1))
                        
                    # 2. check the current level for symmetry
                    while depth and queue:
                        try:
                            (l, lpos), (r, rpos) = queue.pop(0), queue.pop()
                            assert (l.val == r.val) and (lpos == (1 << depth) - 1 - rpos)
                        except:
                            return False
    
                    # 3. proceed to next level
                    queue, depth = tmpq, depth + 1
            
            return True
                                
                    
                
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.