LC 102 - Binary Tree Level Order Traversal
LC 102 - Binary Tree Level Order Traversal
Question
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).
Example 1:
1
2
Input: root = [3,9,20,null,null,15,7]
Output: [[3],[9,20],[15,7]]
Example 2:
1
2
Input: root = [1]
Output: [[1]]
Example 3:
1
2
Input: root = []
Output: []
Constraints:
- The number of nodes in the tree is in the range
[0, 2000]. -1000 <= Node.val <= 1000
Links
Question here and solution here
Solution
concept
This is just a standard BFS.
code
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# 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 []
q = deque([root])
ans = []
while q:
lvl = []
for _ in range(len(q)):
node = q.popleft()
if node:
lvl.append(node.val)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
ans.append(lvl)
return ans
class NeetSolution:
"""
Very similar to the above solution
"""
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
res = []
q = deque()
if root:
q.append(root)
while q:
val = []
for i in range(len(q)):
node = q.popleft()
# note the difference here
# we first add node.val then check if node.left and node.right exist
# hence there is no need to check if val is empty.
# we are adding the node.val to the val list first
val.append(node.val)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
res.append(val)
return res
Complexity
time: $O(n)$
space: $O(n)$
This post is licensed under CC BY 4.0 by the author.
