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 node 10 # @return a boolean 11 def isSymmetric(self,root): 12 ret = True 13 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 = 0 20 t = len(s) - 1 21 while (h < t): 22 if (s[h] != s[t]): 23 ret = False 24 break 25 h+=1#这里忘记控制h和t了 26 t-=1 27 tq = q 28 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
找我内推: 字节跳动各种岗位
作者:
ZH奶酪(张贺)
邮箱:
cheesezh@qq.com
出处:
http://www.cnblogs.com/CheeseZH/
*
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。