Minimum Depth of a Binary Tree (easy)
We'll cover the following
Problem Statement #
Find the minimum depth of a binary tree. The minimum depth is the number of nodes along the shortest path from the root node to the nearest leaf node.
Example 1:
Example 2:
Try it yourself #
Try solving this question here:
Solution #
This problem follows the Binary Tree Level Order Traversal pattern. We can follow the same BFS approach. The only difference will be, instead of keeping track of all the nodes in a level, we will only track the depth of the tree. As soon as we find our first leaf node, that level will represent the minimum depth of the tree.
Code #
Here is what our algorithm will look like, only the highlighted lines have changed:
Time complexity #
The time complexity of the above algorithm is , where āNā is the total number of nodes in the tree. This is due to the fact that we traverse each node once.
Space complexity #
The space complexity of the above algorithm will be which is required for the queue. Since we can have a maximum of nodes at any level (this could happen only at the lowest level), therefore we will need space to store them in the queue.
Similar Problems #
Problem 1: Given a binary tree, find its maximum depth (or height).
Solution: We will follow a similar approach. Instead of returning as soon as we find a leaf node, we will keep traversing for all the levels, incrementing maximumDepth
each time we complete a level. Here is what the code will look like: