The Wayback Machine - https://web.archive.org/web/20240717180319/https://www.geeksforgeeks.org/bottom-view-of-a-binary-tree-using-recursion/
Open In App

Bottom View of a Binary Tree using Recursion

Last Updated : 15 Aug, 2022
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

Given a binary tree, the task is to find the bottom view of a binary tree using recursion.

Examples:

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

Approach:
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:  

C++




#include <bits/stdc++.h>
using namespace std;
 
struct Node {
    int data;
    // left and right references
    Node *left, *right;
    // Constructor of tree Node
    Node(int key)
    {
        data = key;
        left = right = NULL;
    }
};
 
int l = 0, r = 0;
int N;
 
// Function to generate bottom view of binary tree
void Bottom(Node* root, int arr[], int arr2[], int x, int p,
            int mid)
{
    // Base case
    if (root == NULL)
        return;
    // To store leftmost value of x in l
 
    if (x < l)
        l = x;
 
    // To store rightmost value of x in r
    if (x > r)
        r = x;
 
    // To check if arr is empty at mid+x
    if (arr[mid + x] == INT_MIN) {
        // Insert data of Node at arr[mid+x]
        arr[mid + x] = root->data;
        // Insert priority of that Node at arr2[mid+x]
        arr2[mid + x] = p;
    }
 
    // If not empty and priotiy of previously inserted Node
    // is less than current*/
    else if (arr2[mid + x] < p) {
        // Insert current Node data at arr[mid+x]
        arr[mid + x] = root->data;
        // Insert priotiy of that Node at arr2[mid +x]
        arr2[mid + x] = p;
    }
 
    // Go right first then left
    Bottom(root->right, arr, arr2, x + 1, p + 1, mid);
    Bottom(root->left, arr, arr2, x - 1, p + 1, mid);
}
 
// Utility function to generate bottom view of a biany tree
void bottomView(struct Node* root)
{
    int arr[2 * N + 1];
    int arr2[2 * N + 1];
    for (int i = 0; i < 2 * N + 1; i++) {
        arr[i] = INT_MIN;
        arr2[i] = INT_MIN;
    }
    int mid = N, x = 0, p = 0;
    Bottom(root, arr, arr2, x, p, mid);
    for (int i = mid + l; i <= mid + r; i++)
        cout << arr[i] << " ";
}
 
// Driver code
int main()
{
 
    N = 5;
    Node* root = new Node(1);
    root->right = new Node(2);
    root->right->right = new Node(4);
    root->right->right->left = new Node(3);
    root->right->right->right = new Node(5);
 
    bottomView(root);
 
    return 0;
}
 
// This code is contributed by Sania Kumari Gupta
// (kriSania804)


C




#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
 
typedef struct Node {
    int data;
    struct Node *left, *right;
} Node;
 
/* Helper function that allocates a new node with the
   given data and NULL left and right pointers. */
Node* newNode(int data)
{
    Node* new_node = (Node*)malloc(sizeof(Node));
    new_node->data = data;
    new_node->left = new_node->right = NULL;
    return new_node;
}
 
int l = 0, r = 0;
int N;
 
// Function to generate bottom view of binary tree
void Bottom(Node* root, int arr[], int arr2[], int x, int p,
            int mid)
{
    // Base case
    if (root == NULL)
        return;
    // To store leftmost value of x in l
    if (x < l)
        l = x;
    // To store rightmost value of x in r
    if (x > r)
        r = x;
    // To check if arr is empty at mid+x
    if (arr[mid + x] == INT_MIN) {
        // Insert data of Node at arr[mid+x]
        arr[mid + x] = root->data;
        // Insert priority of that Node at arr2[mid+x]
        arr2[mid + x] = p;
    }
 
    // If not empty and priotiy of previously inserted Node
    // is less than current*/
    else if (arr2[mid + x] < p) {
        // Insert current Node data at arr[mid+x]
        arr[mid + x] = root->data;
        // Insert priotiy of that Node at arr2[mid +x]
        arr2[mid + x] = p;
    }
 
    // Go right first then left
    Bottom(root->right, arr, arr2, x + 1, p + 1, mid);
    Bottom(root->left, arr, arr2, x - 1, p + 1, mid);
}
 
// Utility function to generate bottom view of a biany tree
void bottomView(struct Node* root)
{
    int arr[2 * N + 1];
    int arr2[2 * N + 1];
    for (int i = 0; i < 2 * N + 1; i++) {
        arr[i] = INT_MIN;
        arr2[i] = INT_MIN;
    }
    int mid = N, x = 0, p = 0;
    Bottom(root, arr, arr2, x, p, mid);
    for (int i = mid + l; i <= mid + r; i++)
        printf("%d ", arr[i]);
}
 
// Driver code
int main()
{
 
    N = 5;
    Node* root = newNode(1);
    root->right = newNode(2);
    root->right->right = newNode(4);
    root->right->right->left = newNode(3);
    root->right->right->right = newNode(5);
 
    bottomView(root);
 
    return 0;
}
 
// This code is contributed by Sania Kumari Gupta
// (kriSania804)


Java




class GFG {
    static class Node {
        int data;
        // left and right references
        Node left, right;
        // Constructor of tree Node
        public Node(int key)
        {
            data = key;
            left = right = null;
        }
    };
 
    static int l = 0, r = 0, N;
 
    // Function to generate bottom view of binary tree
    static void Bottom(Node root, int arr[], int arr2[],
                       int x, int p, int mid)
    {
        // Base case
        if (root == null)
            return;
        // To store leftmost value of x in l
        if (x < l)
            l = x;
        // To store rightmost value of x in r
        if (x > r)
            r = x;
        // To check if arr is empty at mid+x
        if (arr[mid + x] == Integer.MIN_VALUE) {
            // Insert data of Node at arr[mid+x]
            arr[mid + x] = root.data;
            // Insert priority of that Node at arr2[mid+x]
            arr2[mid + x] = p;
        }
 
        // If not empty and priotiy of previously inserted
        // Node is less than current
        else if (arr2[mid + x] < p) {
 
            // Insert current Node data at arr[mid+x]
            arr[mid + x] = root.data;
 
            // Insert priotiy of that Node at arr2[mid +x]
            arr2[mid + x] = p;
        }
 
        // Go right first then left
        Bottom(root.right, arr, arr2, x + 1, p + 1, mid);
        Bottom(root.left, arr, arr2, x - 1, p + 1, mid);
    }
 
    // Utility function to generate bottom view of a biany
    // tree
    static void bottomView(Node root)
    {
        int[] arr = new int[2 * N + 1];
        int[] arr2 = new int[2 * N + 1];
 
        for (int i = 0; i < 2 * N + 1; i++) {
            arr[i] = Integer.MIN_VALUE;
            arr2[i] = Integer.MIN_VALUE;
        }
        int mid = N, x = 0, p = 0;
        Bottom(root, arr, arr2, x, p, mid);
        for (int i = mid + l; i <= mid + r; i++)
            System.out.print(arr[i] + " ");
    }
 
    // Driver code
    public static void main(String[] args)
    {
        N = 5;
 
        Node root = new Node(1);
        root.right = new Node(2);
        root.right.right = new Node(4);
        root.right.right.left = new Node(3);
        root.right.right.right = new Node(5);
 
        bottomView(root);
    }
}
 
// This code is contributed by Sania Kumari Gupta
// (kriSania804)


Python3




class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
l = 0
r = 0
INT_MIN = -(2**32)
 
# Function to generate
# bottom view of
# binary tree
def Bottom(root, arr, arr2, x, p, mid):
    global INT_MIN, l, r
     
    # Base case
    if (root == None):
        return
     
    if (x < l):
         
        # To store leftmost
        # value of x in l
        l = x
     
    # To store rightmost
    # value of x in r
    if (x > r):
        r = x
         
    # To check if arr
    # is empty at mid+x
    if (arr[mid + x] == INT_MIN):
 
        # Insert data of Node
        # at arr[mid+x]
        arr[mid + x] = root.data
 
        # Insert priority of
        # that Node at arr2[mid+x]
        arr2[mid + x] = p
         
    # If not empty and priotiy
    # of previously inserted
    # Node is less than current*/
    elif (arr2[mid + x] < p):
 
        # Insert current
        # Node data at arr[mid+x]
        arr[mid + x] = root.data
         
        # Insert priotiy of
        # that Node at arr2[mid +x]
        arr2[mid + x] = p
     
    # Go right first
    # then left
    Bottom(root.right, arr, arr2, x + 1, p + 1, mid)
    Bottom(root.left, arr, arr2, x - 1, p + 1, mid)
 
# Utility function
# to generate bottom
# view of a biany tree
def bottomView(root):
    global INT_MIN
    arr = [0]*(2 * N + 1)
    arr2 = [0]*(2 * N + 1)
     
    for i in range(2 * N + 1):
        arr[i] = INT_MIN
        arr2[i] = INT_MIN
    mid = N
    x = 0
    p = 0
    Bottom(root, arr, arr2, x, p, mid)
     
    for i in range(mid + l,mid + r + 1):
        print(arr[i], end = " ")
         
# Driver code
N = 5
root = Node(1)
root.right = Node(2)
root.right.right = Node(4)
root.right.right.left = Node(3)
root.right.right.right = Node(5)
 
bottomView(root)
     
# This code is contributed by SHUBHAMSINGH10


C#




using System;
 
class GFG{
     
class Node{
     
public int data;
 
// left and right references
public Node left, right;
 
// Constructor of tree Node
public Node(int key)
{
    data = key;
    left = right = null;
}
};
 
static int l = 0, r = 0, N;
 
// Function to generate
// bottom view of binary tree
static void Bottom(Node root, int []arr,
                  int []arr2, int x,
                       int p, int mid)
{
     
    // Base case
    if (root == null)
    {
        return;
    }
 
    if (x < l)
    {
         
        // To store leftmost
        // value of x in l
        l = x;
    }
 
    // To store rightmost
    // value of x in r
    if (x > r)
    {
        r = x;
    }
 
    // To check if arr
    // is empty at mid+x
    if (arr[mid + x] == Int32.MinValue)
    {
         
        // Insert data of Node
        // at arr[mid+x]
        arr[mid + x] = root.data;
         
        // Insert priority of
        // that Node at arr2[mid+x]
        arr2[mid + x] = p;
    }
 
    // If not empty and priotiy
    // of previously inserted
    // Node is less than current*/
    else if (arr2[mid + x] < p)
    {
         
        // Insert current
        // Node data at arr[mid+x]
        arr[mid + x] = root.data;
 
        // Insert priotiy of
        // that Node at arr2[mid +x]
        arr2[mid + x] = p;
    }
 
    // Go right first
    // then left
    Bottom(root.right, arr, arr2,
           x + 1, p + 1, mid);
    Bottom(root.left, arr, arr2,
           x - 1, p + 1, mid);
}
 
// Utility function to generate
// bottom view of a biany tree
static void bottomView(Node root)
{
    int[] arr = new int[2 * N + 1];
    int[] arr2 = new int[2 * N + 1];
 
    for(int i = 0; i < 2 * N + 1; i++)
    {
        arr[i] = Int32.MinValue;
        arr2[i] = Int32.MinValue;
    }
 
    int mid = N, x = 0, p = 0;
 
    Bottom(root, arr, arr2, x, p, mid);
 
    for(int i = mid + l; i <= mid + r; i++)
    {
        Console.Write(arr[i] + " ");
    }
}
 
// Driver code
public static void Main(string[] args)
{
    N = 5;
     
    Node root = new Node(1);
    root.right = new Node(2);
    root.right.right = new Node(4);
    root.right.right.left = new Node(3);
    root.right.right.right = new Node(5);
 
    bottomView(root);
}
}
 
// This code is contributed by rutvik_56


Javascript




<script>
 
class Node{
 
    // Constructor of tree Node
    constructor(key)
    {
        this.data = key;
        this.left = null;
        this.right = null;
    }
 
};
 
var l = 0, r = 0, N;
 
// Function to generate
// bottom view of binary tree
function Bottom(root, arr, arr2, x, p, mid)
{
     
    // Base case
    if (root == null)
    {
        return;
    }
 
    if (x < l)
    {
         
        // To store leftmost
        // value of x in l
        l = x;
    }
 
    // To store rightmost
    // value of x in r
    if (x > r)
    {
        r = x;
    }
 
    // To check if arr
    // is empty at mid+x
    if (arr[mid + x] == -1000000000)
    {
         
        // Insert data of Node
        // at arr[mid+x]
        arr[mid + x] = root.data;
         
        // Insert priority of
        // that Node at arr2[mid+x]
        arr2[mid + x] = p;
    }
 
    // If not empty and priotiy
    // of previously inserted
    // Node is less than current*/
    else if (arr2[mid + x] < p)
    {
         
        // Insert current
        // Node data at arr[mid+x]
        arr[mid + x] = root.data;
 
        // Insert priotiy of
        // that Node at arr2[mid +x]
        arr2[mid + x] = p;
    }
 
    // Go right first
    // then left
    Bottom(root.right, arr, arr2,
           x + 1, p + 1, mid);
    Bottom(root.left, arr, arr2,
           x - 1, p + 1, mid);
}
 
// Utility function to generate
// bottom view of a biany tree
function bottomView(root)
{
    var arr = Array(2*N +1).fill(-1000000000);
    var arr2 = Array(2*N +1).fill(-1000000000);
   
    var mid = N, x = 0, p = 0;
 
    Bottom(root, arr, arr2, x, p, mid);
 
    for(var i = mid + l; i <= mid + r; i++)
    {
        document.write(arr[i] + " ");
    }
}
 
// Driver code
N = 5;
 
var root = new Node(1);
root.right = new Node(2);
root.right.right = new Node(4);
root.right.right.left = new Node(3);
root.right.right.right = new Node(5);
bottomView(root);
 
</script>


Output: 

1 3 4 5

 

Time Complexity: O(N) where N is number of nodes in a given binary tree

Auxiliary space: O(n) for implicit call stack as using recursion



Previous Article
Next Article

Similar Reads

Print Bottom-Right View of a Binary Tree
Given a Binary Tree, print Bottom-Right view of it. The Bottom Right view of a Binary Tree is a set of nodes visible when the tree is visited from Bottom Right side, return the values of the nodes ordered from right to left. In the bottom-right view, on viewing the tree at an angle of 45 degrees from the bottom-right side and only a few nodes would
11 min read
Bottom View of a Binary Tree
Given a Binary Tree, The task is 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. The horizontal distance of the left child of a node x is equal to a horizontal distance of x minus 1, and that of a right child is the horizontal distance of x plus 1. Examples: Input: 20
15+ min read
Sum of nodes in bottom view of Binary Tree
Given a binary tree, the task is to print the sum of nodes in the bottom view of the given Binary Tree. The bottom view of a binary tree is the set of nodes visible when the tree is viewed from the bottom. Examples: Input : 1 / \ 2 3 / \ \ 4 5 6Output : 20Input : 1 / \ 2 3 \ 4 \ 5 \ 6Output : 17Approach: The idea is to use a queue. Put tree nodes i
15+ min read
Traverse the matrix in Diagonally Bottom-Up fashion using Recursion
Given a matrix mat[][] of size N x N, the task is to traverse the matrix Diagonally in Bottom-up fashion using recursion.Diagonally Bottom-up Traversal: Traverse the major-diagonal of the matrix.Traverse the bottom diagonal to the major-diagonal of the matrix.Traverse the up diagonal to the major-diagonal of the matrix.Similarly, Traverse the matri
9 min read
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
In this article, we will discuss the complexity of different operations in binary trees including BST and AVL trees. Before understanding this article, you should have a basic idea about Binary Tree, Binary Search Tree, and AVL Tree. The main operations in a binary tree are: search, insert and delete. We will see the worst-case time complexity of t
4 min read
Convert a Binary Tree into its Mirror Tree (Invert Binary Tree)
Given a binary tree, the task is to convert the binary tree into its Mirror tree. Mirror of a Binary Tree T is another Binary Tree M(T) with left and right children of all non-leaf nodes interchanged. Recommended PracticeMirror TreeTry It!The idea is to traverse recursively and swap the right and left subtrees after traversing the subtrees. Follow
15+ min read
Why is Tail Recursion optimization faster than normal Recursion?
What is tail recursion? Tail recursion is defined as a recursive function in which the recursive call is the last statement that is executed by the function. So basically nothing is left to execute after the recursion call. What is non-tail recursion? Non-tail or head recursion is defined as a recursive function in which the recursive call is the f
4 min read
Leaf nodes from Preorder of a Binary Search Tree (Using Recursion)
Given Preorder traversal of a Binary Search Tree. Then the task is to print leaf nodes of the Binary Search Tree from the given preorder. Examples : Input : preorder[] = {890, 325, 290, 530, 965}; Output : 290 530 965 Tree represented is, 890 / \ 325 965 / \ 290 530 Input : preorder[] = { 3, 2, 4 }; Output : 2 4 In this post, a simple recursive sol
5 min read
Find the node with minimum value in a Binary Search Tree using recursion
Given a Binary Search Tree, the task is to find the node with minimum value. Examples: Input: Output: 4 Approach: Just traverse the node from root to left recursively until left is NULL. The node whose left is NULL is the node with the minimum value. Below is the implementation of the above approach: C/C++ Code // C++ implementation of the approach
7 min read
Find the node with maximum value in a Binary Search Tree using recursion
Given a Binary Search Tree, the task is to find the node with maximum value. Examples: Input: Output: 22 Approach: Just traverse the node from root to right recursively until right is NULL. The node whose right is NULL is the node with the maximum value. Below is the implementation of the above approach: C/C++ Code // C++ implementation of the appr
7 min read
Practice Tags :
three90RightbarBannerImg