My Python solution using stack


  • 0
    L
    # 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 is None:
                return True
            
            stack_left = list()
            stack_right = list()
            
            self.push_left_first(root.left, stack_left)
            self.push_right_first(root.right, stack_right)
            
            if len(stack_left) != len(stack_right):
                return False
            while len(stack_left) > 0:
                if stack_left.pop() != stack_right.pop():
                    return False
            return True
                
        def push_left_first(self, node, stack):
            if node:
                stack.append(node.val)
                self.push_left_first(node.left, stack)
                self.push_left_first(node.right, stack)
            else:
                stack.append(None)
        
        def push_right_first(self, node, stack):
            if node:
                stack.append(node.val)
                self.push_right_first(node.right, stack)
                self.push_right_first(node.left, stack)
            else:
                stack.append(None)

Log in to reply
 

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