题目
给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。
示例:
二叉树:[3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
解题思路
Basic problem for tree level order, we use a queue to keep track of nodes we visited, and a pointer points to rightest node of current level. When we encounter the rightest node, we update the pointer to the end of the queue.
Time complexity:
o
(
n
)
o(n)
o(n)
Space complexity:
o
(
n
)
o(n)
o(n)
代码
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
if not root:
return []
queue = collections.deque([root])
cur_level_end = root
res = [[]]
while queue:
node = queue.popleft()
res[-1].append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
if node == cur_level_end and queue:
cur_level_end = queue[-1]
res.append([])
return res