【LeetCode】102.Binary Tree Level Order Traversal

【Description】

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

For example:
Given binary tree [3,9,20,null,null,15,7],
3
/
9 20
/
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]

【Idea】
這個(gè)題也不難, 因?yàn)镺(n)還蠻能打的, 所以po一下
BFS要更好寫一些。 這里每層遍歷node時(shí)直接用了for,沒有用queue,不然還要另起個(gè)變量標(biāo)記

【Solution】

# 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 []
        
        cur = [root]
        res = []
        while cur:
            cur_vals = []
            nextList = []
            for node in cur:
                cur_vals.append(node.val)
                if node.left:
                    nextList.append(node.left)
                if node.right:
                    nextList.append(node.right)
            cur = nextList
            res.append(cur_vals) 
        return res     

image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容