The number of nodes in the tree is in the range [0, 2000].
-1000 <= Node.val <= 1000
Solutions
Solution 1: BFS
Thinking
We must emit values level by level. DFS can record depth and group later, but then left-to-right order needs extra work. \(n \le 2000\), and a level holds at most \(O(n)\) nodes.
BFS expands by level: the nodes currently in the queue are exactly one level. Dequeue them, collect values, and enqueue children to form the next level from left to right.
We can use the BFS method to solve this problem. First, enqueue the root node, then continuously perform the following operations until the queue is empty:
Traverse all nodes in the current queue, store their values in a temporary array \(t\), and then enqueue their child nodes.
Store the temporary array \(t\) in the answer array.
Finally, return the answer array.
The time complexity is \(O(n)\), and the space complexity is \(O(n)\). Here, \(n\) is the number of nodes in the binary tree.
1 2 3 4 5 6 7 8 91011121314151617181920212223
# 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 = rightclassSolution:deflevelOrder(self,root:Optional[TreeNode])->List[List[int]]:ans=[]ifrootisNone:returnansq=deque([root])whileq:t=[]for_inrange(len(q)):node=q.popleft()t.append(node.val)ifnode.left:q.append(node.left)ifnode.right:q.append(node.right)ans.append(t)returnans
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funclevelOrder(root*TreeNode)(ans[][]int){ifroot==nil{return}q:=[]*TreeNode{root}forlen(q)>0{t:=[]int{}forn:=len(q);n>0;n--{node:=q[0]q=q[1:]t=append(t,node.Val)ifnode.Left!=nil{q=append(q,node.Left)}ifnode.Right!=nil{q=append(q,node.Right)}}ans=append(ans,t)}return}