102. Binary Tree Level Order Traversal
Problem
Given the root
of a binary tree, return the level order traversal of its nodes’ values . (i.e., from left to right, level by level).
https://leetcode.com/problems/binary-tree-level-order-traversal/
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: [[3],[9,20],[15,7]]
Example 2:
Input: root = [1]
Output: [[1]]
Example 3:
Input: root = []
Output: []
Constraints:
The number of nodes in the tree is in the range [0, 2000]
.
-1000 <= Node.val <= 1000
Test Cases
1 2 3 4 5 6 7 8 class Solution : def levelOrder (self, root: Optional [TreeNode] ) -> List [List [int ]]:
solution_test.py 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 import pytestimport syssys.path.append('..' ) from _utils.binary_tree import build_treefrom solution import Solutionnull = None @pytest.mark.parametrize('root, expected' , [ ([3 ,9 ,20 ,null,null,15 ,7 ], [[3 ],[9 ,20 ],[15 ,7 ]] ), ([1 ], [[1 ]] ), ([], [] ), ] )class Test : def test_solution (self, root, expected ): sol = Solution() assert sol.levelOrder(build_tree(root)) == expected
Thoughts
直接按层序(level-order)遍历,可以用队列加循环。待处理的节点加入队列时,同时把该节点的层数一起放入队列。节点的层数等于其父节点的层数加一。
Code
solution.py 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 from collections import dequefrom typing import Optional import syssys.path.append('..' ) from _utils.binary_tree import TreeNodeclass Solution : def levelOrder (self, root: Optional [TreeNode] ) -> list [list [int ]]: values = [] queue = deque() queue.append((root, 0 )) while len (queue) > 0 : root, level = queue.popleft() if root is None : continue if level >= len (values): values.append([]) values[-1 ].append(root.val) queue.append((root.left, level + 1 )) queue.append((root.right, level + 1 )) return values