您好,登錄后才能下訂單哦!
給定一個(gè)二叉樹,返回其按層次遍歷的節(jié)點(diǎn)值。 (即逐層地,從左到右訪問所有節(jié)點(diǎn))。
例如:
給定二叉樹:?[3,9,20,null,null,15,7]
,
????3 ???/?\ ??9??20 ????/??\ ???15???7
返回其層次遍歷結(jié)果:
[ ??[3], ??[9,20], ??[15,7] ]
#?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?not?root: ????????????return?[] ????????res?=?[] ????????cur_node?=?[root] ????????next_node?=?[] ????????res.append([i.val?for?i?in?cur_node]) ????????while?cur_node?or?next_node: ????????????for?node?in?cur_node: ????????????????if?node.left: ????????????????????next_node.append(node.left) ????????????????if?node.right: ????????????????????next_node.append(node.right) ????????????if?next_node: ????????????????res.append([ ????????????????????i.val?for?i?in?next_node ????????????????]) ????????????cur_node?=?next_node ????????????next_node?=?[] ????????return?res
執(zhí)行用時(shí) :?80 ms, 在Binary Tree Level Order Traversal的Python3提交中擊敗了26.32% 的用戶
內(nèi)存消耗 :?13.2 MB, 在Binary Tree Level Order Traversal的Python3提交中擊敗了98.08% 的用戶
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。