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             

 

转载于:https://www.cnblogs.com/tingyu-yudeyinji/p/4771023.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值