題目描述
給定一個二叉樹,返回其按層次遍歷的節(jié)點值。 (即逐層地,從左到右訪問所有節(jié)點)息尺。
例如:
給定二叉樹: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其層次遍歷結(jié)果:
[
[3],
[9,20],
[15,7]
]
知識點
二叉樹携兵、層次遍歷
Qiang的思路
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
if root==None:
return []
list=[root,'#']
result=[]
cur=[]
while list!=['#']:
c=list[0]
list.pop(0)
if c=='#':
list.append('#')
result.append(cur)
cur=[]
else:
list.append(c.left) if c.left!=None else None
list.append(c.right) if c.right!=None else None
cur.append(c.val)
result.append(cur)
return result
作者原創(chuàng)疾掰,如需轉(zhuǎn)載及其他問題請郵箱聯(lián)系:lwqiang_chn@163.com。
個人網(wǎng)站:https://www.myqiang.top徐紧。