Symmetric Tree

题目描述

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

For example, this binary tree is symmetric:

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

But the following is not:

    1
   / \
  2   2
   \   \
   3    3

解题方法

这一题一开始理解错了,并不是symmetric tree的subtree也要是symmetric tree,而是

  • left.val == right.val
  • if exists, left.right.val == right.left.val
  • if exists, left.left.val == right.right.val

将这个过程recursive地apply到每应该对称的Node上

所以做题前要想清楚,最好画出几个图来看清楚

Solution

# 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 not root:
            return True
        return self.sym(root.left, root.right)

    def sym(self, n1, n2):
        if not n1 and not n2:
            return True
        if n1 and n2 and n1.val == n2.val:
            return self.sym(n1.left, n2.right) and self.sym(n1.right, n2.left)

        return False

Reference