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

 

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

confused what "{1,#,2,3}" means? 

解题思路:

将根节点的左右孩子分开当做两个树来处理,注意它是要几何对称,所以左边的树的左孩子和右边树的右孩子相互比较。

 1 class Solution(object):
 2     def isSymmetric(self, root):
 3         """
 4         :type root: TreeNode
 5         :rtype: bool
 6         """
 7         from collections import deque
 8         
 9         if not root:
10             return True
11             
12         p = root.left
13         q = root.right
14         
15         if p == None and q != None:
16             return False
17         elif p != None and q == None:
18             return False
19         elif p == None and q == None:
20             return True
21         else:
22             pqueue = deque([p])
23             qqueue = deque([q])
24             
25             while pqueue and qqueue:
26                 nodep = pqueue.popleft()
27                 nodeq = qqueue.popleft()
28                 
29                 if nodep.val != nodeq.val:
30                     return False
31                 else:
32                     if nodep.left and nodeq.right:
33                         pqueue.append(nodep.left)
34                         qqueue.append(nodeq.right)
35                     elif nodep.left == None and nodeq.right != None:
36                         return False
37                     elif nodep.left != None and nodeq.right == None:
38                         return False
39                     else:
40                         pass
41                     
42                     if nodep.right and nodeq.left:
43                         pqueue.append(nodep.right)
44                         qqueue.append(nodeq.left)
45                     elif nodep.right == None and nodeq.left != None:
46                         return False
47                     elif nodep.right != None and nodeq.left == None:
48                         return False
49                     else:
50                         pass
51                 
52         return True
53             

 

posted @ 2015-08-30 15:51  双音节的秋  阅读(131)  评论(0编辑  收藏  举报