In this post, we will discuss a method to print the Bottom view of a binary tree. This is one the most common easy level interview questions. Also, you might get to see interview questions which can be solved with slight variations to this code. We will use a method that is very similar to printing Top View of a Binary Tree as discussed in our last post.
Bottom View of a tree is defined as the nodes that would be visible to us if we viewed the tree from the bottom. To do this we have to maintain a horizontal distance of all the nodes from the root node and print the last node for each horizontal distance. This problem can be solved easily with simple traversal and use of data structures. Have a look at the below image to get some idea.
In the above image, the horizontal distance of the root is set to 0 and for all the node to the right we increase the horizontal distance by 1 and for all the node to the right, we decrease the horizontal distance by 1. Thus, the problem reduces to printing the last node with each horizontal distance. So, we use a map structure to solve this problem.
Let's have a look at the code.
Bottom View of a tree is defined as the nodes that would be visible to us if we viewed the tree from the bottom. To do this we have to maintain a horizontal distance of all the nodes from the root node and print the last node for each horizontal distance. This problem can be solved easily with simple traversal and use of data structures. Have a look at the below image to get some idea.
Bottom View of a Binary Tree |
In the above image, the horizontal distance of the root is set to 0 and for all the node to the right we increase the horizontal distance by 1 and for all the node to the right, we decrease the horizontal distance by 1. Thus, the problem reduces to printing the last node with each horizontal distance. So, we use a map structure to solve this problem.
Let's have a look at the code.
C++ Program
Sample input and output to check the program
You might also be interested in
Top View of a Binary Tree
Left View of a Binary Tree
Right View of a Binary Tree
Comments
Post a Comment