Python DFS with deque, quite symmetric


  • 0
    from collections import deque
    class Solution(object):
        def isSymmetric(self, root):
            """
            :type root: TreeNode
            :rtype: bool
            """
            if root == None or root.left == None and root.right == None: return True
            if root.left == None or root.right == None: return False
            queue = deque([root.left, root.right])
            while queue:
                pleft = queue.popleft()
                pright = queue.pop()
                if pleft.val != pright.val:
                    return False
                if pleft.right != None and pright.left != None:
                    queue.appendleft(pleft.right)
                    queue.append(pright.left)
                elif pleft.right != None or pright.left != None:
                    return False
                if pleft.left != None and pright.right != None:
                    queue.appendleft(pleft.left)
                    queue.append(pright.right)
                elif pleft.left != None or pright.right != None:
                    return False
            return True  
    

Log in to reply
 

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