給定一個二叉樹,返回其按層次遍歷的節(jié)點值。 (即逐層地,從左到右訪問所有節(jié)點)。
成都創(chuàng)新互聯(lián)擁有一支富有激情的企業(yè)網(wǎng)站制作團隊,在互聯(lián)網(wǎng)網(wǎng)站建設(shè)行業(yè)深耕十多年,專業(yè)且經(jīng)驗豐富。十多年網(wǎng)站優(yōu)化營銷經(jīng)驗,我們已為上千家中小企業(yè)提供了成都做網(wǎng)站、網(wǎng)站制作解決方案,按需定制開發(fā),設(shè)計滿意,售后服務(wù)無憂。所有客戶皆提供一年免費網(wǎng)站維護!
例如:
給定二叉樹:?[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í)行用時 :?80 ms, 在Binary Tree Level Order Traversal的Python3提交中擊敗了26.32% 的用戶
內(nèi)存消耗 :?13.2 MB, 在Binary Tree Level Order Traversal的Python3提交中擊敗了98.08% 的用戶