leetcode103
思路1:
- 打算建立兩個(gè)隊(duì)列L1,L2,用BFS方法去搜索,
- 當(dāng)前列表設(shè)置為L(zhǎng)1,然后搜索L1的節(jié)點(diǎn),搜索一個(gè)就彈出一個(gè),并把搜到的節(jié)點(diǎn)都添加到L2中
- 搜索完L1以后,此時(shí)L1為空,L2代表的是下一層的節(jié)點(diǎn)。此時(shí)再把當(dāng)前隊(duì)列設(shè)置為L(zhǎng)2,然后進(jìn)行上面的循環(huán)。
- 循環(huán)結(jié)束條件,兩個(gè)list都為空時(shí),說(shuō)明循環(huán)就可以停止了。
思路2:
- 為了使代碼簡(jiǎn)單些,把讀取下一行,把下一行節(jié)點(diǎn)插入隊(duì)列,讀取下一行節(jié)點(diǎn)的val步驟單獨(dú)定義成一個(gè)函數(shù)。
- 每次對(duì)新的一行進(jìn)行搜索時(shí),調(diào)用此函數(shù)即可,然后決定是否反轉(zhuǎn)。
- 循環(huán)結(jié)束條件:新的隊(duì)列為空
代碼:
注意用列表表示隊(duì)列時(shí),每次添加元素都是用insert方法。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
def search_func(Q_para):
Q_res = []
L_res = []
while Q_para:
node = Q_para.pop()
if node.left:
Q_res.insert(0,node.left)
L_res.append(node.left.val)
if node.right:
Q_res.insert(0,node.right)
L_res.append(node.right.val)
return Q_res,L_res
if root:
results = []
Que = [root]
L1 = [root.val]
n = 0
while Que:
if n%2 == 0:
results.append(L1)
else:
L1.reverse()
results.append(L1)
Que,L1 = search_func(Que)
n += 1
return results
else:
return []