How can we say that 5 and 6 are on the same level??
i have disscuss the detail solution of the problem read this
this will be helpful to understand your mistake
Given a Binary Tree, we need to print the bottom view from left to right. A node x is there in output if x is the bottommost node at its horizontal distance.
Horizontal distance of left child of a node x is equal to horizontal distance of x minus 1, and that of right child is horizontal distance of x plus 1.
20 / \ 8 22 / \ \ 5 3 25 / \ 10 14
For the above tree the output should be 5, 10, 3, 14, 25.
If there are multiple bottom-most nodes for a horizontal distance from root, then print the later one in level traversal. For example, in the below diagram, 3 and 4 are both the bottom-most nodes at horizontal distance 0, we need to print 4.
20 / \ 8 22 / \ / \ 5 3 4 25 / \ 10 14
For the above tree the output should be 5, 10, 4, 14, 25.
The following are steps to print Bottom View of Binary Tree.
- We put tree nodes in a queue for the level order traversal.
- Start with the horizontal distance(hd) 0 of the root node, keep on adding left child to queue along with the horizontal distance as hd-1 and right child as hd+1.
- Also, use a TreeMap which stores key value pair sorted on key.
- Every time, we encounter a new horizontal distance or an existing horizontal distance put the node data for the horizontal distance as key. For the first time it will add to the map, next time it will replace the value. This will make sure that the bottom most element for that horizontal distance is present in the map and if you see the tree from beneath that you will see that element.
you can take help from reference Code
if you have more doubts regarding this feel free to ask
i hope this helps
if yes hit a like and don’t forgot to mark doubt as resolved
I haven’t done map as of yet. Is there any other way to do it without using map
you can learn map first
map used in most of the questions
for now skip this question