101. Symmetric Tree

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

But the following [1,2,2,null,3,null,3] is not:

    1
   / \
  2   2
   \   \
   3    3

Note:

Bonus points if you could solve it both recursively and iteratively.

Solution: DFS

class Solution(object):
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if not root:
            return True

        def dfs(left, right):
            if not left and not right:
                return True
            if not left or not right or left.val != right.val:
                return False
            return dfs(left.left, right.right) and dfs(left.right, right.left)

        return dfs(root.left, root.right)

Solution: BFS

class Solution(object):
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        q = [root]
        while q:
            if not self.is_palindrome(q):
                return False
            new_q = []
            for node in q:
                if node:
                    new_q.append(node.left)
                    new_q.append(node.right)
            q = new_q
        return True

    def is_palindrome(self, nodes):
        low = 0
        high = len(nodes) - 1
        while low < high:
            left, right = nodes[low], nodes[high]
            if left and right and left.val != right.val:
                return False
            if (left and not right) or (not left and right):
                return False
            low += 1
            high -= 1
        return True

results matching ""

    No results matching ""