码迷,mamicode.com
首页 > 其他好文 > 详细

101. Symmetric Tree

时间:2017-03-15 16:46:34      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:ret   point   this   迭代   span   round   code   his   efi   

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

标签:ret   point   this   迭代   span   round   code   his   efi   

原文地址:http://www.cnblogs.com/fullest-life/p/6554970.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!