Maximum height of the binary search tree created from the given array

Given an array arr[] of N integers, the task is to make two binary search trees. One while traversing from the left side of the array and another while traversing from the right and find which tree has a greater height.

Examples:

Input: arr[] = {2, 1, 3, 4}
Output: 0
BST starting from first index           BST starting from last index 
    2                                             4
   / \                                           /
  1   3                                         3
       \                                       /
        4                                     1
                                               \
                                                2

Input: arr[] = {1, 2, 6, 3, 5}
Output: 1

Prerequisites: Inserting a node in a Binary Search tree and Finding the height of a binary tree.



Approach:

  • Create a binary search tree while inserting the nodes starting from the first element of the array till the last and find the height of this created tree say leftHeight.
  • Create another binary search tree while inserting the nodes starting from the last element of the array till the first and find the height of this created tree say rightHeight.
  • Print the maximum of these calculated heights i.e. max(leftHeight, rightHeight)

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
  
struct node {
    int key;
    struct node *left, *right;
};
  
// A utility function to create a new BST node
struct node* newNode(int item)
{
    struct node* temp = (struct node*)malloc(sizeof(struct node));
    temp->key = item;
    temp->left = temp->right = NULL;
    return temp;
}
  
/* A utility function to insert a new node with given key in BST */
struct node* insert(struct node* node, int key)
{
    /* If the tree is empty, return a new node */
    if (node == NULL)
        return newNode(key);
  
    /* Otherwise, recur down the tree */
    if (key < node->key)
        node->left = insert(node->left, key);
    else if (key > node->key)
        node->right = insert(node->right, key);
  
    /* return the (unchanged) node pointer */
    return node;
}
  
/* Compute the "maxDepth" of a tree -- the number of 
    nodes along the longest path from the root node 
    down to the farthest leaf node.*/
int maxDepth(node* node)
{
    if (node == NULL)
        return 0;
    else {
        /* compute the depth of each subtree */
        int lDepth = maxDepth(node->left);
        int rDepth = maxDepth(node->right);
  
        /* use the larger one */
        if (lDepth > rDepth)
            return (lDepth + 1);
        else
            return (rDepth + 1);
    }
}
  
// Function to return the maximum
// heights among the BSTs
int maxHeight(int a[], int n)
{
    // Create a BST starting from
    // the first element
    struct node* rootA = NULL;
    rootA = insert(rootA, a[0]);
    for (int i = 1; i < n; i++)
        insert(rootA, a[i]);
  
    // Create another BST starting
    // from the last element
    struct node* rootB = NULL;
    rootB = insert(rootB, a[n - 1]);
    for (int i = n - 2; i >= 0; i--)
        insert(rootB, a[i]);
  
    // Find the heights of both the trees
    int A = maxDepth(rootA) - 1;
    int B = maxDepth(rootB) - 1;
  
    return max(A, B);
}
  
// Driver code
int main()
{
    int a[] = { 2, 1, 3, 4 };
    int n = sizeof(a) / sizeof(a[0]);
  
    cout << maxHeight(a, n);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of the approach
class GFG
{
  
static class node
{
    int key;
    node left, right;
};
  
// A utility function to create a new BST node
static node newNode(int item)
{
    node temp = new node();
    temp.key = item;
    temp.left = temp.right = null;
    return temp;
}
  
/* A utility function to insert 
a new node with given key in BST */
static node insert(node node, int key)
{
    /* If the tree is empty, 
    return a new node */
    if (node == null)
        return newNode(key);
  
    /* Otherwise, recur down the tree */
    if (key < node.key)
        node.left = insert(node.left, key);
    else if (key > node.key)
        node.right = insert(node.right, key);
  
    /* return the (unchanged) node pointer */
    return node;
}
  
/* Compute the "maxDepth" of a tree -- 
the number of nodes along the longest path 
from the root node down to the farthest leaf node.*/
static int maxDepth(node node)
{
    if (node == null)
        return 0;
    else 
    {
          
        /* compute the depth of each subtree */
        int lDepth = maxDepth(node.left);
        int rDepth = maxDepth(node.right);
  
        /* use the larger one */
        if (lDepth > rDepth)
            return (lDepth + 1);
        else
            return (rDepth + 1);
    }
}
  
// Function to return the maximum
// heights among the BSTs
static int maxHeight(int a[], int n)
{
    // Create a BST starting from
    // the first element
    node rootA = null;
    rootA = insert(rootA, a[0]);
    for (int i = 1; i < n; i++)
        rootA = insert(rootA, a[i]);
  
    // Create another BST starting
    // from the last element
    node rootB = null;
    rootB = insert(rootB, a[n - 1]);
    for (int i = n - 2; i >= 0; i--)
        rootB =insert(rootB, a[i]);
  
    // Find the heights of both the trees
    int A = maxDepth(rootA) - 1;
    int B = maxDepth(rootB) - 1;
  
    return Math.max(A, B);
}
  
// Driver code
public static void main(String args[])
{
    int a[] = { 2, 1, 3, 4 };
    int n = a.length;
  
    System.out.println(maxHeight(a, n));
}
}
  
// This code is contributed by Arnab Kundu

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python implementation of the approach
  
class Node:
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None
  
# A utility function to insert
# a new node with given key in BST */
def insert(node: Node, key: int) -> Node:
  
    # If the tree is empty,
    # return a new node */
    if node is None:
        return Node(key)
    # Otherwise, recur down the tree
    if key < node.key:
        node.left = insert(node.left, key)
    elif key > node.key:
        node.right = insert(node.right, key)
  
    # return the (unchanged) node pointer
    return node
  
# Compute the "maxDepth" of a tree --
# the number of nodes along the longest path
# from the root node down to the farthest leaf node.*/
def maxDepth(node: Node) -> int:
    if node is None:
        return 0
    else:
  
        # compute the depth of each subtree
        lDepth = maxDepth(node.left)
        rDepth = maxDepth(node.right)
  
        # use the larger one
        if lDepth > rDepth:
            return lDepth + 1
        else:
            return rDepth + 1
  
# Function to return the maximum
# heights among the BSTs
def maxHeight(a: list, n: int) -> int:
  
    # Create a BST starting from
    # the first element
    rootA = Node(a[0])
    for i in range(1, n):
        rootA = insert(rootA, a[i])
  
    # Create another BST starting
    # from the last element
    rootB = Node(a[n - 1])
    for i in range(n - 2, -1, -1):
        rootB = insert(rootB, a[i])
  
    # Find the heights of both the trees
    A = maxDepth(rootA) - 1
    B = maxDepth(rootB) - 1
  
    return max(A, B)
  
# Driver Code
if __name__ == "__main__":
    a = [2, 1, 3, 4]
    n = len(a)
  
    print(maxHeight(a, n))
  
# This code is contributed by
# sanjeev2552

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of the approach 
using System;
  
class GFG 
    public class node 
    
        public int key; 
        public node left, right; 
    }; 
      
    // A utility function to create a new BST node 
    static node newNode(int item) 
    
        node temp = new node(); 
        temp.key = item; 
        temp.left = temp.right = null
        return temp; 
    
      
    /* A utility function to insert 
    a new node with given key in BST */
    static node insert(node node, int key) 
    
        /* If the tree is empty, 
        return a new node */
        if (node == null
            return newNode(key); 
      
        /* Otherwise, recur down the tree */
        if (key < node.key) 
            node.left = insert(node.left, key); 
        else if (key > node.key) 
            node.right = insert(node.right, key); 
      
        /* return the (unchanged) node pointer */
        return node; 
    
      
    /* Compute the "maxDepth" of a tree -- 
    the number of nodes along the longest path 
    from the root node down to the farthest leaf node.*/
    static int maxDepth(node node) 
    
        if (node == null
            return 0; 
        else
        
              
            /* compute the depth of each subtree */
            int lDepth = maxDepth(node.left); 
            int rDepth = maxDepth(node.right); 
      
            /* use the larger one */
            if (lDepth > rDepth) 
                return (lDepth + 1); 
            else
                return (rDepth + 1); 
        
    
      
    // Function to return the maximum 
    // heights among the BSTs 
    static int maxHeight(int []a, int n) 
    
        // Create a BST starting from 
        // the first element 
        node rootA = null
        rootA = insert(rootA, a[0]); 
        for (int i = 1; i < n; i++) 
            rootA = insert(rootA, a[i]); 
      
        // Create another BST starting 
        // from the last element 
        node rootB = null
        rootB = insert(rootB, a[n - 1]); 
        for (int i = n - 2; i >= 0; i--) 
            rootB =insert(rootB, a[i]); 
      
        // Find the heights of both the trees 
        int A = maxDepth(rootA) - 1; 
        int B = maxDepth(rootB) - 1; 
      
        return Math.Max(A, B); 
    
      
    // Driver code 
    public static void Main() 
    
        int []a = { 2, 1, 3, 4 }; 
        int n = a.Length; 
      
        Console.WriteLine(maxHeight(a, n)); 
    
  
// This code is contributed by AnkitRai01 

chevron_right


Output:

3

GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.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.