Solving Binary Tree Level Order Traversal
Marhaba 👋🏼
Welcome to another article on solving programming problems in Swift. I’ll be covering the Binary Tree Level Order Traversal problem.
Yalla, let’s begin.
Table of Contents
Problem Statement
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:
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: []
Here’s the initial code below without a solution.
Problem Analysis
Without thinking about code, let’s envision a level-order traversal step by step starting with the root node.
Did you notice a pattern? Let’s notate some observations from our analysis:
We started with
root
, collecting its value and children invalues
andchildren
To proceed to the next level, we iterate through all
children
in a first-in, first-out sequence. As withroot
, we updatevalues
andchildren.
We continue until all levels are exhausted.
Based on our knowledge of data structures and algorithms we know:
A Queue data structure is required
Iterating via level-by-level resembles a breadth-first search algorithm.
Now that we have everything we need to implement our solution, let’s code!
Solution
First, I’ll cover an edge case for when the root
node is nil,
which will return an empty list. Assuming our root node is not nil
, then I’ll proceed with initializing a queue with the root node and a multi-dimensional array with the root node value.
Remember, queue
will track child nodes while finalElements
will track values at each level.
Next, I’ll set up the following:
A while loop, which will terminate when the queue is empty.
Create a
tempQueue
, which is a copy of the current queueClear our current queue (you’ll see why in a second)
Initialize an empty
elements
array, which will track values at each level
Next, I’ll create an inner while loop that will:
Traverse through all nodes in
tempQueue
using first-in-first-out order.If node has a left child and/or a right child, then:
Add its value to
elements
Add child node to original
queue
Once all nodes of
tempQueue
are exhausted (level traversal completion), then we add collected values tofinalElements
Looking good so far. Our last step is returning finalElements
. Here’s the full solution below:
Results
Time Complexity: O(n)
LeetCode Performance:
For any comments and questions on this post, follow up on Twitter.
Make sure to share this article. Appreciate you reading through my blog and until next time.