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奶酪博客园博客,原文链接:http://www.cnblogs.com/CheeseZH/p/4033695.html,如需转载请自行联系原作者

相关文章
|
4月前
|
存储 索引 Python
leetcode-350:两个数组的交集 II(python中Counter的用法,海象运算符:=)
leetcode-350:两个数组的交集 II(python中Counter的用法,海象运算符:=)
31 0
|
20天前
|
API Python
[AIGC] 使用Python刷LeetCode:常用API及技巧指南
[AIGC] 使用Python刷LeetCode:常用API及技巧指南
|
4月前
|
算法 索引 Python
leetcode-138:复制带随机指针的链表 (python中copy与deepcopy区别)
leetcode-138:复制带随机指针的链表 (python中copy与deepcopy区别)
36 0
|
5月前
|
开发者 索引 Python
【python刷题】LeetCode 2057E 值相等的最小索引(5种简单高效的解法)
【python刷题】LeetCode 2057E 值相等的最小索引(5种简单高效的解法)
28 0
|
11月前
|
Python
Python|leetcode-访问所有点的最小时间
Python|leetcode-访问所有点的最小时间
53 0
|
12月前
|
Python
Python|Leetcode《539》|最小时间差
Python|Leetcode《539》|最小时间差
|
12月前
|
Python
Python|Leetcode《1220》|统计元音字母序列的数目
Python|Leetcode《1220》|统计元音字母序列的数目
|
12月前
|
Python
Python|Leetcode《334》|递增的三元子序列
Python|Leetcode《334》|递增的三元子序列
|
5天前
|
算法 C++
【刷题】Leetcode 1609.奇偶树
这道题是我目前做过最难的题,虽然没有一遍做出来,但是参考大佬的代码,慢慢啃的感觉的真的很好。刷题继续!!!!!!
8 0
|
5天前
|
算法 索引
【刷题】滑动窗口精通 — Leetcode 30. 串联所有单词的子串 | Leetcode 76. 最小覆盖子串
经过这两道题目的书写,相信大家一定深刻认识到了滑动窗口的使用方法!!! 下面请大家继续刷题吧!!!
10 0