【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】
这个题也不难, 因为O(n)还蛮能打的, 所以po一下
BFS要更好写一些。 这里每层遍历node时直接用了for,没有用queue,不然还要另起个变量标记
【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