moonlightshadow123
6/22/2017 - 4:23 AM

101. Symmetric Tree

  1. Symmetric Tree
# 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 == None:
            return True
        return self.check(root.left, root.right)
    def check(self, node1, node2):
        if node1 == None and node2 == None:
            return True
        elif node1 == None or node2 == None:
            return False
        else:
            cond1 = node1.val == node2.val
            cond2 = self.check(node1.right, node2.left)
            cond3 = self.check(node1.left, node2.right)
            return cond1 and cond2 and cond3

https://leetcode.com/problems/symmetric-tree/#/description

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