Given a binary tree, print the bottom view from left to right
All Answers
total answers (1)
Severity: 8192
Message: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated
Filename: libraries/Filtered_db.php
Line Number: 23
total answers (1)
What is bottom view?
Bottom view is not only the leaf nodes. We can consider the tree like below: (same as the problem of finding vertical sum)
For the above tree, let's check what the vertical sum is for the tree,
Just consider, we have partitioned the tree nodes into column & rows where rows are the level no starting from 0. Then the above tree can be converted into the above table easily.
Then column of next node = column of current node-1
Else
Column of next node = column of current node+1
Using the above steps the tree can be easily partitioned to the table. It is to observe that there may be several entries at a specific (row, column) position. Like here, at Level3, column no 1 has two entry 11 & 4.
Rest is about printing the last entry (bottommost) in each column. If there are multiple entries in the bottommost (in this case 11 & 4 for col 1) the last one entry is taken only.
Thus the output should be 2, 5, 6, 4, 9 (from col -2 to col 2 direction).
Though the visual description seems to be very easy to solve this problem, in programming view it's not that easy.
Algorithm to find vertical sum
The basic concept is to do pre-order traversal & while traversing we will keep track for each column (hashing) & make the entry.
Thus the column no is used as key & we need a map to process our algorithm.
Call findbottom(root, 0, hash);
C++ implementation
Output