因?yàn)樵趯懽钚∩疃扔脤哟伪闅v時(shí)候?qū)戇^,代碼如下
res=[]
if not root :
return res
q=[root]
while q:
for i in range(len(q)):
r=q.pop(0)
if r.left:
q.append(r.left)
if r.right:
q.append(r.right)
res.append(r.val)
return res
但是,在leetcode上運(yùn)行時(shí)候發(fā)現(xiàn)它的輸出有個(gè)嵌套隊(duì)列,于是代碼加個(gè)s隊(duì)列
res=[]
if not root :
return res
q=[root]
while q:
s=[]
for i in range(len(q)):
r=q.pop(0)
s.append(r.val)
if r.left:
q.append(r.left)
if r.right:
q.append(r.right)
res.append(s)
return res