Bottom View of a Binary Tree using Recursion
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
Time Complexity: O(N) where N is number of nodes in a given binary tree