首页 > 代码库 > 101. Symmetric Tree

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(迭代).

 

 1 # Definition for a binary tree node.
 2 # class TreeNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.left = None
 6 #         self.right = None
 7 
 8 class Solution(object):
 9     def isSymmetric(self, root):
10         """
11         :type root: TreeNode
12         :rtype: bool
13         """
14         if not root: return True
15         return self.helper(root.left, root.right)
16 
17     def helper(self, left, right):
18     # first make sure left and right is not none
19         if left and right: 
20             if left.val == right.val:
21                 return self.helper(left.left, right.right) and self.helper(left.right, right.left)
22             else:
23                 return False
24         else:
25     # otherwise,return left == right
26             return left == right 

 

101. Symmetric Tree