Problem
Given a binary tree, print it in Bottom View of it.
The horizontal distance of a binary tree node describes how far left or right the node will be when the tree is printed out.
More rigorously, we can define it as follows:
- The horizontal distance of the root is
0
. - The horizontal distance of a left child is
hd(parent) - 1
. - The horizontal distance of a right child is
hd(parent) + 1
.
For example, for the following tree, hd(1) = -2
, and hd(6) = 0
.
The bottom view of a tree, then, consists of the lowest node at each horizontal distance. If there are two nodes at the same depth and horizontal distance, either is acceptable.
What is Bottom View?
Bottom view means when you look the tree from the bottom the nodes you will see will be called the bottom view of the tree.
Examples
Example 1:
|
|
Solution
This problem is quite similar to the -
Just modified the code so that it will print only the last element it will encounter in the vertical order. That will be the bottom view.
How will you know that you are visiting the last node at every level(Vertically)?
- Take a variable called level, whenever you go left, do level++ AND whenever you go right do level–. By level we mean here horizontal differential OR HD.
- With step above we have separated out the levels vertically.
In top view, we care about the first element added to hashmap, but in bottom view we consider till the last element added for that distance.
Method 1 - Iterative BFS
To get the bottom view of a binary tree, we use a level order traversal (Breadth-First Search) while keeping track of horizontal distances of nodes in a dictionary. Each level’s elements are stored in the dictionary with the key as the horizontal distance and value as the node at that level. We iterate through the TreeMap at the end to print the bottom view.
Approach
- Initialize Data Structures: Start with initializing a queue and a dictionary (Map) where each key-value pair will be (horizontal distance, node value).
- Breadth-First Search: Implement a level order traversal (BFS) with a queue, keeping track of horizontal distances.
- Track Nodes: Store only the most recently visited node at each horizontal distance (i.e., the last node at each level).
- Result Extraction: After BFS traversal, extract the values in the dictionary in the order of their horizontal distances to form the bottom view.
See the code for better understanding.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
- wheren
is the number of nodes in the binary tree. Each node is visited once. - 🧺 Space complexity:
O(n)
- due to the storage of nodes in the queue and the dictionary.