Very straightforward, a level order traversal is the same thing as BFS. You arrive at a node, put it’s neighbours in a queue to be visited later. Make sure to also maintain a another loop inside your main BFS loop so that you keep track of “levels”.
Code:
Java
Big O Analysis
-
Runtime
The runtime complexity here is
O(N)
as since we would be iterating the array atleast once. -
Memory
The memory usage is
O(1)
since we are not using any extra datastructure.
— A