首页 > 代码库 > leetcode:Symmetric Tree【Python版】

leetcode:Symmetric Tree【Python版】

#error caused by:
#1:{} 没有考虑None输入
#2:{1,2,2} 没有控制h和t
#3:{4,-57,-57,#,67,67,#,#,-97,-97} 没有考虑负号,将s从str变成list,采用9999代表空数值;

---------------------

逐层进行对称性验证,出现不对称就结束;

 1 # Definition for a  binary tree node 2 # class TreeNode: 3 #     def __init__(self, x): 4 #         self.val = x 5 #         self.left = None 6 #         self.right = None 7  8 class Solution: 9     # @param root, a tree node10     # @return a boolean11     def isSymmetric(self,root):12         ret = True13         q = []14         s = []15         if root != None:#注意root为空16             q.append(root)17             s.append(root.val)18         while (len(q) != 0 and ret == True):19             h = 020             t = len(s) - 121             while (h < t):22                 if (s[h] != s[t]):23                     ret = False24                     break25                 h+=1#这里忘记控制h和t了26                 t-=127             tq = q28             s = []29             q = []30             while (len(tq) != 0 and ret == True):31                 t = tq.pop(0)#pop默认弹出最后一个值32                 if t.left != None:33                     q.append(t.left)34                     s.append(t.left.val)35                 else:36                     s.append(9999)37                 if t.right != None:38                     q.append(t.right)39                     s.append(t.right.val)40                 else:41                     s.append(9999)42         return ret

 

leetcode:Symmetric Tree【Python版】