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
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- 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 nodes of a Binary Search Tree in Top Level Order and Reversed Bottom Level Order alternately
- Leaf nodes from Preorder of a Binary Search Tree (Using Recursion)
- Zig-Zag traversal of a Binary Tree using Recursion
- Find the node with minimum value in a Binary Search Tree using recursion
- Find the node with maximum value in a Binary Search Tree using recursion
- Find maximum and minimum element in binary tree without using recursion or stack or queue
- Find Maximum Level Sum in Binary Tree using Recursion
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Print Right View of a Binary Tree
- Print Nodes in Top View of Binary Tree
- Print nodes in the Top View of Binary Tree | Set 3
- Iterative Method To Print Left View of a Binary Tree
- Sum of nodes in top view of binary tree
- Sum of nodes in the right view of the given binary tree
- Sum of nodes in the left view of the given binary tree
- Print nodes in top view of Binary Tree | Set 2
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.