Given a binary tree, the task is to find the bottom view of a binary tree using recursion.
Input: 1 \ 2 \ 4 / \ 3 5 Output: 1 3 4 5 Input: 20 / \ 8 22 / \ / \ 5 10 21 25 / \ 9 14 Output: 5 9 21 14 25
We can do so by using recursion and 2 arrays each with size 2n+1(for worst case), where n = number of elements in the given tree. Here, we take a Variable x which determines its Horizontal Distance. Let x is the horizontal distance of a Node. Now, the left child will have a horizontal distance of x-1(x minus 1)and the right child will have horizontal distance x+1(x plus 1). Take another Variable ‘p’ as a priority which will decide which level this element belongs to.
1 (x=0, p=0) \ 2 (x=1, p=1) \ 4 (x=2, p=2) / \ (x=1, p=3) 3 5 (x=3, p=3)
While Traversing the Tree In fashion Right-> Node-> Left, assign x and p to each Node and simultaneously insert the data of node in the first array if the array is empty at position (mid+x). If the array is not empty and a Node with higher Priority( p ) comes to update the array with the data of this Node as position(mid+x). The second array will be maintaining the priority( p ) of each inserted node in the first array check code for better understanding.
Below is the implementation of above approach:
1 3 4 5
- Bottom View of a Binary Tree
- Print Bottom-Right View of a Binary Tree
- Sum of nodes in bottom view of Binary Tree
- Right view of Binary Tree using Queue
- Print Right View of a Binary Tree
- Sum of nodes in the right view of the given binary tree
- Sum of nodes in top view of binary tree
- Print nodes in the Top View of Binary Tree | Set 3
- Print nodes in top view of Binary Tree | Set 2
- Sum of nodes in the left view of the given binary tree
- Print Left View of a Binary Tree
- Print Nodes in Top View of Binary Tree
- Iterative Method To Print Left View of a Binary Tree
- Zig-Zag traversal of a Binary Tree using Recursion
- Find Maximum Level Sum in Binary Tree using Recursion
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.