Open In App
Related Articles

Introduction to Binary Search Tree – Data Structure and Algorithm Tutorials

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

A Binary Search Tree (BST) is a special type of binary tree in which the left child of a node has a value less than the node’s value and the right child has a value greater than the node’s value. This property is called the BST property and it makes it possible to efficiently search, insert, and delete elements in the tree.

The root of a BST is the node that has the smallest value in the left subtree and the largest value in the right subtree. Each left subtree is a BST with nodes that have smaller values than the root and each right subtree is a BST with nodes that have larger values than the root.

Binary Search Tree is a node-based binary tree data structure that has the following properties: 

  • The left subtree of a node contains only nodes with keys lesser than the node’s key.
  • The right subtree of a node contains only nodes with keys greater than the node’s key.
  • This means everything to the left of the root is less than the value of the root and everything to the right of the root is greater than the value of the root. Due to this performing, a binary search is very easy.
  • The left and right subtree each must also be a binary search tree.  
    There must be no duplicate nodes(BST may have duplicate values with different handling approaches)

Handling approach for Duplicate values in the Binary Search tree:

  • You can not allow the duplicated values at all.
  • We must follow a consistent process throughout i.e either store duplicate value at the left or store the duplicate value at the right of the root, but be consistent with your approach.
  • We can keep the counter with the node and if we found the duplicate value, then we can increment the counter

Below are the various operations that can be performed on a BST:

  • Insert a node into a BST: A new key is always inserted at the leaf. Start searching a key from the root till a leaf node. Once a leaf node is found, the new node is added as a child of the leaf node.

C++

// C++ program to insert a node
// in a BST
#include <bits/stdc++.h>
using namespace std;
 
// Given Node
struct node
{
    int key;
    struct node *left, *right;
};
 
// 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;
}
 
// 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 node pointer
    return node;
}
 
// Function to do inorder traversal of BST
void inorder(struct node* root)
{
    if (root != NULL)
    {
        inorder(root->left);
        cout << root->key << " ";
        inorder(root->right);
    }
}
 
// Driver Code
int main()
{
     
    /* Let us create following BST
              50
           /     \
          30      70
         /  \    /  \
       20   40  60   80
   */
    struct node* root = NULL;
 
    // Inserting value 50
    root = insert(root, 50);
 
    // Inserting value 30
    insert(root, 30);
 
    // Inserting value 20
    insert(root, 20);
 
    // Inserting value 40
    insert(root, 40);
 
    // Inserting value 70
    insert(root, 70);
 
    // Inserting value 60
    insert(root, 60);
 
    // Inserting value 80
    insert(root, 80);
 
    // Print the BST
    inorder(root);
 
    return 0;
}
 
// This code is contributed by shubhamsingh10

                    

C

// C program to insert a node
// in a BST
#include <stdio.h>
#include <stdlib.h>
 
// Given Node
struct node {
    int key;
    struct node *left, *right;
};
 
// 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;
}
 
// 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 node pointer
    return node;
}
 
// Function to do inorder traversal of BST
void inorder(struct node* root)
{
    if (root != NULL) {
        inorder(root->left);
        printf("%d ", root->key);
        inorder(root->right);
    }
}
 
// Driver Code
int main()
{
    /* Let us create following BST
              50
           /     \
          30      70
         /  \    /  \
       20   40  60   80
   */
    struct node* root = NULL;
 
    // inserting value 50
    root = insert(root, 50);
 
    // inserting value 30
    insert(root, 30);
 
    // inserting value 20
    insert(root, 20);
 
    // inserting value 40
    insert(root, 40);
 
    // inserting value 70
    insert(root, 70);
 
    // inserting value 60
    insert(root, 60);
 
    // inserting value 80
    insert(root, 80);
 
    // print the BST
    inorder(root);
 
    return 0;
}

                    

Java

import java.io.*;
 
// Java program for Inserting a node
class GFG {
 
    // Given Node
    static class node {
        int key;
        node left, right;
    };
 
    // 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;
    }
 
    // 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 node
        return node;
    }
 
    // Function to do inorder traversal of BST
    static void inorder(node root)
    {
        if (root != null) {
            inorder(root.left);
            System.out.print(" " + root.key);
            inorder(root.right);
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        /* Let us create following BST
                50
             /     \
            30      70
           /  \    /  \
         20   40  60   80
     */
        node root = null;
 
        // inserting value 50
        root = insert(root, 50);
 
        // inserting value 30
        insert(root, 30);
 
        // inserting value 20
        insert(root, 20);
 
        // inserting value 40
        insert(root, 40);
 
        // inserting value 70
        insert(root, 70);
 
        // inserting value 60
        insert(root, 60);
 
        // inserting value 80
        insert(root, 80);
 
        // print the BST
        inorder(root);
    }
}
// This code is contributed by abhijitjadhav1998

                    

Python3

# Python program to insert a node
# in a BST
 
# Given Node
class Node:
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None
 
# Function to insert a new node with
# given key in BST
def insert(node, key):
    # 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 node pointer
    return node
 
# Function to do inorder traversal of BST
def inorder(root):
    if root is not None:
        inorder(root.left)
        print(root.key, end=" ")
        inorder(root.right)
 
# Driver Code
if __name__ == '__main__':
    """
    Let us create following BST
          50
       /     \
      30      70
     /  \    /  \
    20  40  60   80
    """
    root = None
 
    # Inserting value 50
    root = insert(root, 50)
 
    # Inserting value 30
    insert(root, 30)
 
    # Inserting value 20
    insert(root, 20)
 
    # Inserting value 40
    insert(root, 40)
 
    # Inserting value 70
    insert(root, 70)
 
    # Inserting value 60
    insert(root, 60)
 
    # Inserting value 80
    insert(root, 80)
 
    # Print the BST
    inorder(root)
     
#This code is contributed by japmeet01

                    

Javascript

// javascript program to insert a node
// in a BST
 
// Given Node
class Node
{
     
    constructor(key){
        this.key = key;
        this.left = null;
        this.right = null;
    }
 
}
 
 
// Function to insert a new node with
// given key in BST
function insert(node, key)
{
     
    // If the tree is empty, return a new node
    if (node == null)
        return new Node(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 node pointer
    return node;
}
 
// Function to do inorder traversal of BST
function inorder(root)
{
    if (root != null)
    {
        inorder(root.left);
        document.write(root.key + " ");
        inorder(root.right);
    }
}
 
// Driver Code
 
/* Let us create following BST
          50
       /     \
      30      70
     /  \    /  \
   20   40  60   80
*/
let root = null;
 
// Inserting value 50
root = insert(root, 50);
 
// Inserting value 30
root = insert(root, 30);
 
// Inserting value 20
root = insert(root, 20);
 
// Inserting value 40
root = insert(root, 40);
 
// Inserting value 70
root = insert(root, 70);
 
// Inserting value 60
root = insert(root, 60);
 
// Inserting value 80
root = insert(root, 80);
 
// Print the BST
inorder(root);
 
 
// This code is contributed by Arushi Jindal.

                    

Output
20 30 40 50 60 70 80 

Time Complexity: O(N), where N is the number of nodes of the BST 
Auxiliary Space: O(1) 

  • Inorder traversal: In case of binary search trees (BST), Inorder traversal gives nodes in non-decreasing order. We visit the left child first, then the root, and then the right child.

C++

// C++ program to implement
// inorder traversal of BST
#include <bits/stdc++.h>
using namespace std;
 
// Given Node node
struct node
{
    int key;
    struct node *left, *right;
};
 
// 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;
}
 
// 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 node pointer
    return node;
}
 
// Function to do inorder traversal of BST
void inorder(struct node* root)
{
    if (root != NULL)
    {
        inorder(root->left);
        cout << " " << root->key;
        inorder(root->right);
    }
}
 
// Driver Code
int main()
{
     
    /* Let us create following BST
              50
           /     \
          30      70
         /  \    /  \
       20   40  60   80
   */
    struct node* root = NULL;
 
    // Creating the BST
    root = insert(root, 50);
    insert(root, 30);
    insert(root, 20);
    insert(root, 40);
    insert(root, 70);
    insert(root, 60);
    insert(root, 80);
 
    // Function Call
    inorder(root);
 
    return 0;
}
 
// This code is contributed by shivanisinghss2110

                    

C

// C program to implement
// inorder traversal of BST
#include <stdio.h>
#include <stdlib.h>
 
// Given Node node
struct node {
    int key;
    struct node *left, *right;
};
 
// 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;
}
 
// 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 node pointer
    return node;
}
 
// Function to do inorder traversal of BST
void inorder(struct node* root)
{
    if (root != NULL) {
        inorder(root->left);
        printf("%d ", root->key);
        inorder(root->right);
    }
}
 
// Driver Code
int main()
{
    /* Let us create following BST
              50
           /     \
          30      70
         /  \    /  \
       20   40  60   80
   */
    struct node* root = NULL;
 
    // Creating the BST
    root = insert(root, 50);
    insert(root, 30);
    insert(root, 20);
    insert(root, 40);
    insert(root, 70);
    insert(root, 60);
    insert(root, 80);
 
    // Function Call
    inorder(root);
 
    return 0;
}

                    

Java

import java.io.*;
 
// Java program for Inorder Traversal
class GFG {
 
    // Given Node node
    static class node {
        int key;
        node left, right;
    };
 
    // 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;
    }
 
    // 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 node
        return node;
    }
 
    // Function to do inorder traversal of BST
    static void inorder(node root)
    {
        if (root != null) {
            inorder(root.left);
            System.out.print(" " + root.key);
            inorder(root.right);
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        /* Let us create following BST
                50
             /     \
            30      70
           /  \    /  \
         20   40  60   80
     */
        node root = null;
 
        // inserting value 50
        root = insert(root, 50);
 
        // inserting value 30
        insert(root, 30);
 
        // inserting value 20
        insert(root, 20);
 
        // inserting value 40
        insert(root, 40);
 
        // inserting value 70
        insert(root, 70);
 
        // inserting value 60
        insert(root, 60);
 
        // inserting value 80
        insert(root, 80);
 
        // print the BST
        inorder(root);
    }
}
// This code is contributed by abhijitjadhav1998

                    

Python3

# Python program to implement
# inorder traversal of BST
 
# Given Node node
class Node:
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None
 
# Function to create a new BST node
def newNode(item):
    temp = Node(item)
    temp.key = item
    temp.left = temp.right = None
    return temp
 
# Function to insert a new node with
# given key in BST
def insert(node, key):
    # If the tree is empty, return a new node
    if node is None:
        return newNode(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 node pointer
    return node
 
# Function to do inorder traversal of BST
def inorder(root):
    if root:
        inorder(root.left)
        print(root.key, end=" ")
        inorder(root.right)
 
# Driver Code
if __name__ == '__main__':
     
    # Let us create following BST
    #          50
    #       /     \
    #     30      70
    #    /  \    /  \
    #  20   40  60   80
    root = None
 
    # Creating the BST
    root = insert(root, 50)
    insert(root, 30)
    insert(root, 20)
    insert(root, 40)
    insert(root, 70)
    insert(root, 60)
    insert(root, 80)
 
    # Function Call
    inorder(root)
#This code is contributed by japmeet01

                    

Output
 20 30 40 50 60 70 80

Time Complexity: O(N), where N is the number of nodes of the BST 
Auxiliary Space: O(1) 

  • Preorder traversal: Preorder traversal first visits the root node and then traverses the left and the right subtree. It is used to create a copy of the tree. Preorder traversal is also used to get prefix expression on of an expression tree.

C++

// C++ program to implement
// preorder traversal
#include <bits/stdc++.h>
using namespace std;
 
// Given Node node
struct node {
    int key;
    struct node *left, *right;
};
 
// 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;
}
 
// 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 node pointer
    return node;
}
 
// Function to do preorder traversal of BST
void preOrder(struct node* root)
{
    if (root != NULL) {
        cout << " " << root->key;
        preOrder(root->left);
        preOrder(root->right);
    }
}
 
// Driver Code
int main()
{
    /* Let us create following BST
              50
           /     \
          30      70
         /  \    /  \
       20   40  60   80
   */
    struct node* root = NULL;
 
    // Creating the BST
    root = insert(root, 50);
    insert(root, 30);
    insert(root, 20);
    insert(root, 40);
    insert(root, 70);
    insert(root, 60);
    insert(root, 80);
 
    // Function Call
    preOrder(root);
 
    return 0;
}
// this code is contributed by shivanisinghss2110

                    

C

// C program to implement
// preorder traversal
#include <stdio.h>
#include <stdlib.h>
 
// Given Node node
struct node {
    int key;
    struct node *left, *right;
};
 
// 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;
}
 
// 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 node pointer
    return node;
}
 
// Function to do preorder traversal of BST
void preOrder(struct node* root)
{
    if (root != NULL) {
        printf("%d ", root->key);
        preOrder(root->left);
        preOrder(root->right);
    }
}
 
// Driver Code
int main()
{
    /* Let us create following BST
              50
           /     \
          30      70
         /  \    /  \
       20   40  60   80
   */
    struct node* root = NULL;
 
    // Creating the BST
    root = insert(root, 50);
    insert(root, 30);
    insert(root, 20);
    insert(root, 40);
    insert(root, 70);
    insert(root, 60);
    insert(root, 80);
 
    // Function Call
    preOrder(root);
 
    return 0;
}

                    

Java

import java.io.*;
 
// Java program for Preorder Traversal
class GFG {
 
    // Given Node node
    static class node {
        int key;
        node left, right;
    };
 
    // 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;
    }
 
    // 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 node
        return node;
    }
 
    // Function to do preorder traversal of BST
    static void preOrder(node root)
    {
        if (root != null) {
            System.out.print(root.key + " ");
            preOrder(root.left);
            preOrder(root.right);
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        /* Let us create following BST
                50
             /     \
            30      70
           /  \    /  \
         20   40  60   80
     */
        node root = null;
 
        // inserting value 50
        root = insert(root, 50);
 
        // inserting value 30
        insert(root, 30);
 
        // inserting value 20
        insert(root, 20);
 
        // inserting value 40
        insert(root, 40);
 
        // inserting value 70
        insert(root, 70);
 
        // inserting value 60
        insert(root, 60);
 
        // inserting value 80
        insert(root, 80);
 
        // print the BST
        preOrder(root);
    }
}
// This code is contributed by abhijitjadhav1998

                    

Python3

# Python program to implement preorder traversal
class Node:
    # Constructor to create a new node
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None
 
# Function to insert a new node with
# given key in BST
 
 
def insert(node, key):
    # 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 node pointer
    return node
 
# Function to do preorder traversal of BST
 
 
def preOrder(root):
    if root:
        print(root.key, end=" ")
        preOrder(root.left)
        preOrder(root.right)
 
 
# Driver Code
if __name__ == '__main__':
    """
        Let us create following BST
              50
           /     \
          30      70
         /  \    /  \
       20   40  60   80
   """
    root = None
    keys = [50, 30, 20, 40, 70, 60, 80]
 
    # Creating the BST
    for key in keys:
        root = insert(root, key)
 
    # Function Call
    preOrder(root)
#This code is contributed by japmeet01

                    

Output
 50 30 20 40 70 60 80

Time Complexity: O(N), where N is the number of nodes of the BST 
Auxiliary Space: O(1) 

  • Postorder traversal: Postorder traversal first traverses the left and the right subtree and then visits the root node. It is used to delete the tree. In simple words, visit the root of every subtree last.

C++

// C++ program to print total
// count of nodes in BST
#include <iostream>
using namespace std;
 
// Given Node node
struct node
{
    int key;
    struct node *left, *right;
};
 
// 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;
}
 
// 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 node pointer
    return node;
}
 
// Function to do postorder traversal of BST
void postOrder(struct node* root)
{
    if (root != NULL)
    {
        postOrder(root->left);
        postOrder(root->right);
        cout << " " << root->key;
    }
}
 
// Driver Code
int main()
{
     
    /* Let us create following BST
              50
           /     \
          30      70
         /  \    /  \
       20   40  60   80
   */
    struct node* root = NULL;
 
    // Creating the BST
    root = insert(root, 50);
    insert(root, 30);
    insert(root, 20);
    insert(root, 40);
    insert(root, 70);
    insert(root, 60);
    insert(root, 80);
 
    // Function Call
    postOrder(root);
 
    return 0;
}
 
// This code is contributed by shivanisinghss2110

                    

C

// C program to implement
// postorder traversal
#include <stdio.h>
#include <stdlib.h>
 
// Given Node node
struct node {
    int key;
    struct node *left, *right;
};
 
// 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;
}
 
// 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 node pointer
    return node;
}
 
// Function to do postorder traversal of BST
void postOrder(struct node* root)
{
    if (root != NULL) {
        postOrder(root->left);
        postOrder(root->right);
        printf("%d ", root->key);
    }
}
 
// Driver Code
int main()
{
    /* Let us create following BST
              50
           /     \
          30      70
         /  \    /  \
       20   40  60   80
   */
    struct node* root = NULL;
 
    // Creating the BST
    root = insert(root, 50);
    insert(root, 30);
    insert(root, 20);
    insert(root, 40);
    insert(root, 70);
    insert(root, 60);
    insert(root, 80);
 
    // Function Call
    postOrder(root);
 
    return 0;
}

                    

Java

import java.io.*;
 
// Java program for Post Order Traversal
class GFG {
 
    // Given Node node
    static class node {
        int key;
        node left, right;
    };
 
    // 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;
    }
 
    // 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 node
        return node;
    }
 
    // Function to do postorder traversal of BST
    static void postOrder(node root)
    {
        if (root != null) {
            postOrder(root.left);
            postOrder(root.right);
            System.out.print(" " + root.key);
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        /* Let us create following BST
                50
             /     \
            30      70
           /  \    /  \
         20   40  60   80
     */
        node root = null;
 
        // inserting value 50
        root = insert(root, 50);
 
        // inserting value 30
        insert(root, 30);
 
        // inserting value 20
        insert(root, 20);
 
        // inserting value 40
        insert(root, 40);
 
        // inserting value 70
        insert(root, 70);
 
        // inserting value 60
        insert(root, 60);
 
        // inserting value 80
        insert(root, 80);
 
        // print the BST
        postOrder(root);
    }
}
// This code is contributed by abhijitjadhav1998

                    

Python3

# Python program to print total count of nodes in BST
 
# Define the Node class
class Node:
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None
 
# Function to insert a new node with given key in BST
def insert(node, key):
    # 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 node pointer
    return node
 
# Function to do postorder traversal of BST
def postOrder(root):
    if root:
        postOrder(root.left)
        postOrder(root.right)
        print(root.key, end=" ")
 
# Driver code
if __name__ == '__main__':
    # Let us create following BST
    #           50
    #        /     \
    #       30      70
    #      /  \    /  \
    #    20   40  60   80
 
    root = None
 
    # Creating the BST
    root = insert(root, 50)
    insert(root, 30)
    insert(root, 20)
    insert(root, 40)
    insert(root, 70)
    insert(root, 60)
    insert(root, 80)
 
    # Function call
    postOrder(root)
 
    #This code is contributed by japmeet01

                    

Output
 20 40 30 60 80 70 50

Time Complexity: O(N), where N is the number of nodes of the BST 
Auxiliary Space: O(1) 

  • Level order traversal: Level order traversal of a BST is breadth first traversal for the tree. It visits all nodes at a particular level first before moving to the next level.

C++

// C++ program to implement
// level order traversal
#include <bits/stdc++.h>
using namespace std;
 
// Given Node node
struct node {
    int key;
    struct node *left, *right;
};
 
// 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;
}
 
// 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 node pointer
    return node;
}
 
// Returns height of the BST
int height(struct node* node)
{
    if (node == NULL)
        return 0;
    else {
 
        // Compute the depth of each subtree
        int lDepth = height(node->left);
        int rDepth = height(node->right);
 
        // Use the larger one
        if (lDepth > rDepth)
            return (lDepth + 1);
        else
            return (rDepth + 1);
    }
}
 
// Print nodes at a given level
void printGivenLevel(struct node* root,
                     int level)
{
    if (root == NULL)
        return;
    if (level == 1)
        cout <<"  "<< root->key;
    else if (level > 1) {
 
        // Recursive Call
        printGivenLevel(root->left, level - 1);
        printGivenLevel(root->right, level - 1);
    }
}
 
// Function to line by line print
// level order traversal a tree
void printLevelOrder(struct node* root)
{
    int h = height(root);
    int i;
    for (i = 1; i <= h; i++) {
        printGivenLevel(root, i);
        cout <<"\n";
    }
}
 
// Driver Code
int main()
{
    /* Let us create following BST
              50
           /     \
          30      70
         /  \    /  \
       20   40  60   80
   */
    struct node* root = NULL;
 
    // Creating the BST
    root = insert(root, 50);
    insert(root, 30);
    insert(root, 20);
    insert(root, 40);
    insert(root, 70);
    insert(root, 60);
    insert(root, 80);
 
    // Function Call
    printLevelOrder(root);
 
    return 0;
}
// this code is contributed by shivanisinghss2110

                    

C

// C program to implement
// level order traversal
#include <stdio.h>
#include <stdlib.h>
 
// Given Node node
struct node {
    int key;
    struct node *left, *right;
};
 
// 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;
}
 
// 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 node pointer
    return node;
}
 
// Returns height of the BST
int height(struct node* node)
{
    if (node == NULL)
        return 0;
    else {
 
        // Compute the depth of each subtree
        int lDepth = height(node->left);
        int rDepth = height(node->right);
 
        // Use the larger one
        if (lDepth > rDepth)
            return (lDepth + 1);
        else
            return (rDepth + 1);
    }
}
 
// Print nodes at a given level
void printGivenLevel(struct node* root,
                     int level)
{
    if (root == NULL)
        return;
    if (level == 1)
        printf("%d ", root->key);
    else if (level > 1) {
 
        // Recursive Call
        printGivenLevel(root->left, level - 1);
        printGivenLevel(root->right, level - 1);
    }
}
 
// Function to line by line print
// level order traversal a tree
void printLevelOrder(struct node* root)
{
    int h = height(root);
    int i;
    for (i = 1; i <= h; i++) {
        printGivenLevel(root, i);
        printf("\n");
    }
}
 
// Driver Code
int main()
{
    /* Let us create following BST
              50
           /     \
          30      70
         /  \    /  \
       20   40  60   80
   */
    struct node* root = NULL;
 
    // Creating the BST
    root = insert(root, 50);
    insert(root, 30);
    insert(root, 20);
    insert(root, 40);
    insert(root, 70);
    insert(root, 60);
    insert(root, 80);
 
    // Function Call
    printLevelOrder(root);
 
    return 0;
}

                    

Java

import java.io.*;
 
// Java program for Level Order Traversal
class GFG {
 
    // Given Node node
    static class node {
        int key;
        node left, right;
    };
 
    // 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;
    }
 
    // 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 node
        return node;
    }
 
    // Returns height of the BST
    static int height(node node)
    {
        if (node == null)
            return 0;
        else {
 
            // Compute the depth of each subtree
            int lDepth = height(node.left);
            int rDepth = height(node.right);
 
            // Use the larger one
            if (lDepth > rDepth)
                return (lDepth + 1);
            else
                return (rDepth + 1);
        }
    }
 
    // Print nodes at a given level
    static void printGivenLevel(node root, int level)
    {
        if (root == null)
            return;
        if (level == 1)
            System.out.print(" " + root.key);
        else if (level > 1) {
 
            // Recursive Call
            printGivenLevel(root.left, level - 1);
            printGivenLevel(root.right, level - 1);
        }
    }
 
    // Function to line by line print
    // level order traversal a tree
    static void printLevelOrder(node root)
    {
        int h = height(root);
        int i;
        for (i = 1; i <= h; i++) {
            printGivenLevel(root, i);
            System.out.println();
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        /* Let us create following BST
                50
             /     \
            30      70
           /  \    /  \
         20   40  60   80
     */
        node root = null;
 
        // inserting value 50
        root = insert(root, 50);
 
        // inserting value 30
        insert(root, 30);
 
        // inserting value 20
        insert(root, 20);
 
        // inserting value 40
        insert(root, 40);
 
        // inserting value 70
        insert(root, 70);
 
        // inserting value 60
        insert(root, 60);
 
        // inserting value 80
        insert(root, 80);
 
        // Function Call
        printLevelOrder(root);
    }
}
// This code is contributed by abhijitjadhav1998

                    

Python3

# Python program to implement
# level order traversal
import queue
 
# Given Node node
class Node:
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None
 
# Function to insert a new node with
# given key in BST
def insert(node, key):
    # 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 node pointer
    return node
 
# Returns height of the BST
def height(node):
    if node is None:
        return 0
    else:
        # Compute the depth of each subtree
        lDepth = height(node.left)
        rDepth = height(node.right)
 
        # Use the larger one
        if lDepth > rDepth:
            return (lDepth + 1)
        else:
            return (rDepth + 1)
 
# Print nodes at a given level
def printGivenLevel(root, level):
    if root is None:
        return
    if level == 1:
        print(root.key, end=" ")
    elif level > 1:
        # Recursive call
        printGivenLevel(root.left, level - 1)
        printGivenLevel(root.right, level - 1)
 
# Function to line by line print
# level order traversal of a tree
def printLevelOrder(root):
    h = height(root)
    for i in range(1, h+1):
        printGivenLevel(root, i)
        print()
 
# Driver Code
if __name__ == '__main__':
    # Let us create following BST
    #          50
    #       /     \
    #      30      70
    #     /  \    /  \
    #   20   40  60   80
    root = None
 
    # Creating the BST
    root = insert(root, 50)
    insert(root, 30)
    insert(root, 20)
    insert(root, 40)
    insert(root, 70)
    insert(root, 60)
    insert(root, 80)
 
    # Function Call
    printLevelOrder(root)
     
    #This code is contributed by japmeet01

                    

Output
  50
  30  70
  20  40  60  80

Time Complexity: O(N), where N is the number of nodes of the BST 
Auxiliary Space: O(1) 

C++

// C++ program to print nodes
// at a given level
#include <bits/stdc++.h>
using namespace std;
 
// Given Node node
struct node {
    int key;
    struct node *left, *right;
};
 
// 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;
}
 
// 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 node pointer
    return node;
}
 
// Print nodes at a given level
void printGivenLevel(struct node* root,
                     int level)
{
    if (root == NULL)
        return;
    if (level == 1)
        cout <<" "<< root->key;
    else if (level > 1) {
 
        // Recursive Call
        printGivenLevel(root->left, level - 1);
        printGivenLevel(root->right, level - 1);
    }
}
 
// Driver Code
int main()
{
    /* Let us create following BST
              50
           /     \
          30      70
         /  \    /  \
       20   40  60   80
   */
    struct node* root = NULL;
 
    // Creating the BST
    root = insert(root, 50);
    insert(root, 30);
    insert(root, 20);
    insert(root, 40);
    insert(root, 70);
    insert(root, 60);
    insert(root, 80);
 
    // Function Call
    printGivenLevel(root, 2);
 
    return 0;
}
// this code is contributed by shivanisinghss2110

                    

C

// C program to print nodes
// at a given level
#include <stdio.h>
#include <stdlib.h>
 
// Given Node node
struct node {
    int key;
    struct node *left, *right;
};
 
// 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;
}
 
// 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 node pointer
    return node;
}
 
// Print nodes at a given level
void printGivenLevel(struct node* root,
                     int level)
{
    if (root == NULL)
        return;
    if (level == 1)
        printf("%d ", root->key);
    else if (level > 1) {
 
        // Recursive Call
        printGivenLevel(root->left, level - 1);
        printGivenLevel(root->right, level - 1);
    }
}
 
// Driver Code
int main()
{
    /* Let us create following BST
              50
           /     \
          30      70
         /  \    /  \
       20   40  60   80
   */
    struct node* root = NULL;
 
    // Creating the BST
    root = insert(root, 50);
    insert(root, 30);
    insert(root, 20);
    insert(root, 40);
    insert(root, 70);
    insert(root, 60);
    insert(root, 80);
 
    // Function Call
    printGivenLevel(root, 2);
 
    return 0;
}

                    

Java

import java.io.*;
 
// Java program for Printing nodes at given level
class GFG {
 
    // Given Node node
    static class node {
        int key;
        node left, right;
    };
 
    // 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;
    }
 
    // 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 node
        return node;
    }
 
    // Print nodes at a given level
    static void printGivenLevel(node root, int level)
    {
        if (root == null)
            return;
        if (level == 1)
            System.out.print(" " + root.key);
        else if (level > 1) {
 
            // Recursive Call
            printGivenLevel(root.left, level - 1);
            printGivenLevel(root.right, level - 1);
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        /* Let us create following BST
                50
             /     \
            30      70
           /  \    /  \
         20   40  60   80
     */
        node root = null;
 
        // inserting value 50
        root = insert(root, 50);
 
        // inserting value 30
        insert(root, 30);
 
        // inserting value 20
        insert(root, 20);
 
        // inserting value 40
        insert(root, 40);
 
        // inserting value 70
        insert(root, 70);
 
        // inserting value 60
        insert(root, 60);
 
        // inserting value 80
        insert(root, 80);
 
        // Function Call
        printGivenLevel(root, 2);
    }
}
// This code is contributed by abhijitjadhav1998

                    

Python3

# Python program to print nodes at a given level
 
# Given Node node
 
 
class Node:
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None
 
# Function to insert a new node with
# given key in BST
 
 
def insert(node, key):
    # 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 node pointer
    return node
 
# Print nodes at a given level
 
 
def printGivenLevel(root, level):
    if root is None:
        return
    if level == 1:
        print(root.key, end=' ')
    elif level > 1:
        # Recursive Call
        printGivenLevel(root.left, level - 1)
        printGivenLevel(root.right, level - 1)
 
 
# Driver Code
if __name__ == '__main__':
    # Let us create following BST
    #           50
    #        /     \
    #       30      70
    #      /  \    /  \
    #     20   40  60   80
    root = None
 
    # Creating the BST
    root = insert(root, 50)
    insert(root, 30)
    insert(root, 20)
    insert(root, 40)
    insert(root, 70)
    insert(root, 60)
    insert(root, 80)
 
    # Function Call
    printGivenLevel(root, 2)
 
    # This code is contributed by japmeet01

                    

Output
 30 70

Time Complexity: O(N), where N is the number of nodes of the BST 
Auxiliary Space: O(1) 

C++

// C++ program to print all
// leaf nodes of a BST
#include <bits/stdc++.h>
using namespace std;
 
// Given Node node
struct node {
    int key;
    struct node *left, *right;
};
 
// 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;
}
 
// 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 node pointer
    return node;
}
 
// Function to print leaf nodes
// from left to right
void printLeafNodes(struct node* root)
{
    // If node is null, return
    if (!root)
        return;
 
    // If node is leaf node,
    // print its data
    if (!root->left && !root->right) {
 
        cout <<" "<< root->key;
        return;
    }
 
    // If left child exists,
    // check for leaf recursively
    if (root->left)
        printLeafNodes(root->left);
 
    // If right child exists,
    // check for leaf recursively
    if (root->right)
        printLeafNodes(root->right);
}
 
// Driver Code
int main()
{
    /* Let us create following BST
              50
           /     \
          30      70
         /  \    /  \
       20   40  60   80
   */
    struct node* root = NULL;
 
    // Creating the BST
    root = insert(root, 50);
    insert(root, 30);
    insert(root, 20);
    insert(root, 40);
    insert(root, 70);
    insert(root, 60);
    insert(root, 80);
 
    // Function Call
    printLeafNodes(root);
 
    return 0;
}
 
// This code is contributed by shivanisinghss2110

                    

C

// C program to print all
// leaf nodes of a BST
#include <stdio.h>
#include <stdlib.h>
 
// Given Node node
struct node {
    int key;
    struct node *left, *right;
};
 
// 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;
}
 
// 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 node pointer
    return node;
}
 
// Function to print leaf nodes
// from left to right
void printLeafNodes(struct node* root)
{
    // If node is null, return
    if (!root)
        return;
 
    // If node is leaf node,
    // print its data
    if (!root->left && !root->right) {
 
        printf("%d ", root->key);
        return;
    }
 
    // If left child exists,
    // check for leaf recursively
    if (root->left)
        printLeafNodes(root->left);
 
    // If right child exists,
    // check for leaf recursively
    if (root->right)
        printLeafNodes(root->right);
}
 
// Driver Code
int main()
{
    /* Let us create following BST
              50
           /     \
          30      70
         /  \    /  \
       20   40  60   80
   */
    struct node* root = NULL;
 
    // Creating the BST
    root = insert(root, 50);
    insert(root, 30);
    insert(root, 20);
    insert(root, 40);
    insert(root, 70);
    insert(root, 60);
    insert(root, 80);
 
    // Function Call
    printLeafNodes(root);
 
    return 0;
}

                    

Java

import java.io.*;
 
// Java program for Printing all leaf nodes
class GFG {
 
    // Given Node node
    static class node {
        int key;
        node left, right;
    };
 
    // 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;
    }
 
    // 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 node
        return node;
    }
 
    // Function to print leaf nodes
    // from left to right
    static void printLeafNodes(node root)
    {
        // If node is null, return
        if (root == null)
            return;
 
        // If node is leaf node,
        // print its data
        if (root.left == null && root.right == null) {
            System.out.print(" " + root.key);
            return;
        }
 
        // If left child exists,
        // check for leaf recursively
        if (root.left != null)
            printLeafNodes(root.left);
 
        // If right child exists,
        // check for leaf recursively
        if (root.right != null)
            printLeafNodes(root.right);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        /* Let us create following BST
                50
             /     \
            30      70
           /  \    /  \
         20   40  60   80
     */
        node root = null;
 
        // inserting value 50
        root = insert(root, 50);
 
        // inserting value 30
        insert(root, 30);
 
        // inserting value 20
        insert(root, 20);
 
        // inserting value 40
        insert(root, 40);
 
        // inserting value 70
        insert(root, 70);
 
        // inserting value 60
        insert(root, 60);
 
        // inserting value 80
        insert(root, 80);
 
        // Function Call
        printLeafNodes(root);
    }
}
// This code is contributed by abhijitjadhav1998

                    

Python3

# Python program to print all
# leaf nodes of a BST
 
# Given Node node
class Node:
    def __init__(self, item):
        self.key = item
        self.left = None
        self.right = None
 
# Function to insert a new node with
# given key in BST
def insert(node, key):
    # 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 node pointer
    return node
 
# Function to print leaf nodes
# from left to right
def printLeafNodes(root):
    # If node is null, return
    if not root:
        return
 
    # If node is leaf node,
    # print its data
    if not root.left and not root.right:
        print(root.key, end=" ")
 
    # If left child exists,
    # check for leaf recursively
    if root.left:
        printLeafNodes(root.left)
 
    # If right child exists,
    # check for leaf recursively
    if root.right:
        printLeafNodes(root.right)
 
# Driver Code
if __name__ == "__main__":
    # Let us create following BST
    #          50
    #        /    \
    #      30      70
    #     /  \    /  \
    #   20   40  60   80
 
    # Creating the BST
    root = None
    root = insert(root, 50)
    insert(root, 30)
    insert(root, 20)
    insert(root, 40)
    insert(root, 70)
    insert(root, 60)
    insert(root, 80)
 
    # Function Call
    printLeafNodes(root)
 
    #This code is contributed by japmeet01

                    

Output
 20 40 60 80

Time Complexity: O(N), where N is the number of nodes of the BST 
Auxiliary Space: O(1) 

C++

// C++ program to print all
// non leaf nodes of a BST
#include <bits/stdc++.h>
using namespace std;
 
// Given Node node
struct node {
    int key;
    struct node *left, *right;
};
 
// 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;
}
 
// 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 node pointer
    return node;
}
 
// Function to print all non-leaf
// nodes in a tree
void printNonLeafNode(struct node* root)
{
    // Base Cases
    if (root == NULL
        || (root->left == NULL
            && root->right == NULL))
        return;
 
    // If current node is non-leaf,
    if (root->left != NULL
        || root->right != NULL) {
        cout <<" "<< root->key;
    }
 
    // If root is Not NULL and its one
    // of its child is also not NULL
    printNonLeafNode(root->left);
    printNonLeafNode(root->right);
}
 
// Driver Code
int main()
{
    /* Let us create following BST
              50
           /     \
          30      70
         /  \    /  \
       20   40  60   80
   */
    struct node* root = NULL;
 
    // Creating the BST
    root = insert(root, 50);
    insert(root, 30);
    insert(root, 20);
    insert(root, 40);
    insert(root, 70);
    insert(root, 60);
    insert(root, 80);
 
    // Function Call
    printNonLeafNode(root);
 
    return 0;
}
 
// This code is contributed by shivanisinghss2110

                    

C

// C program to print all
// non leaf nodes of a BST
#include <stdio.h>
#include <stdlib.h>
 
// Given Node node
struct node {
    int key;
    struct node *left, *right;
};
 
// 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;
}
 
// 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 node pointer
    return node;
}
 
// Function to print all non-leaf
// nodes in a tree
void printNonLeafNode(struct node* root)
{
    // Base Cases
    if (root == NULL
        || (root->left == NULL
            && root->right == NULL))
        return;
 
    // If current node is non-leaf,
    if (root->left != NULL
        || root->right != NULL) {
        printf("%d ", root->key);
    }
 
    // If root is Not NULL and its one
    // of its child is also not NULL
    printNonLeafNode(root->left);
    printNonLeafNode(root->right);
}
 
// Driver Code
int main()
{
    /* Let us create following BST
              50
           /     \
          30      70
         /  \    /  \
       20   40  60   80
   */
    struct node* root = NULL;
 
    // Creating the BST
    root = insert(root, 50);
    insert(root, 30);
    insert(root, 20);
    insert(root, 40);
    insert(root, 70);
    insert(root, 60);
    insert(root, 80);
 
    // Function Call
    printNonLeafNode(root);
 
    return 0;
}

                    

Java

import java.io.*;
 
// Java program for Printing all non leaf nodes
class GFG {
 
    // Given Node node
    static class node {
        int key;
        node left, right;
    };
 
    // 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;
    }
 
    // 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 node
        return node;
    }
 
    // Function to print all non-leaf
    // nodes in a tree
    static void printNonLeafNode(node root)
    {
        // Base Cases
        if (root == null
            || (root.left == null && root.right == null))
            return;
 
        // If current node is non-leaf,
        if (root.left != null || root.right != null) {
            System.out.print(" " + root.key);
        }
 
        // If root is Not NULL and its one
        // of its child is also not NULL
        printNonLeafNode(root.left);
        printNonLeafNode(root.right);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        /* Let us create following BST
                50
             /     \
            30      70
           /  \    /  \
         20   40  60   80
     */
        node root = null;
 
        // inserting value 50
        root = insert(root, 50);
 
        // inserting value 30
        insert(root, 30);
 
        // inserting value 20
        insert(root, 20);
 
        // inserting value 40
        insert(root, 40);
 
        // inserting value 70
        insert(root, 70);
 
        // inserting value 60
        insert(root, 60);
 
        // inserting value 80
        insert(root, 80);
 
        // Function Call
        printNonLeafNode(root);
    }
}
// This code is contributed by abhijitjadhav1998

                    

Python3

# Python program to print all
# non leaf nodes of a BST
 
# Given Node node
 
 
class Node:
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None
 
# Function to insert a new node with
# given key in BST
 
 
def insert(root, key):
    # If the tree is empty, return a new node
    if root is None:
        return Node(key)
 
    # Otherwise, recur down the tree
    if key < root.key:
        root.left = insert(root.left, key)
    elif key > root.key:
        root.right = insert(root.right, key)
 
    # Return the node pointer
    return root
 
# Function to print all non-leaf
# nodes in a tree
 
 
def printNonLeafNode(root):
    # Base Cases
    if root is None or (root.left is None and root.right is None):
        return
 
    # If current node is non-leaf,
    if root.left is not None or root.right is not None:
        print(root.key, end=" ")
 
    # If root is Not NULL and its one
    # of its child is also not NULL
    printNonLeafNode(root.left)
    printNonLeafNode(root.right)
 
 
# Driver Code
if __name__ == '__main__':
    # Let us create following BST
    #           50
    #        /     \
    #      30       70
    #     /  \     /  \
    #   20   40   60   80
 
    root = None
 
    # Creating the BST
    root = insert(root, 50)
    insert(root, 30)
    insert(root, 20)
    insert(root, 40)
    insert(root, 70)
    insert(root, 60)
    insert(root, 80)
 
    # Function Call
    printNonLeafNode(root)
 
    # This code is contributed by japmeet01

                    

Output
 50 30 70

Time Complexity: O(N), where N is the number of nodes of the BST 
Auxiliary Space: O(1) 

  • Right view of BST: Right view of a Binary Search Tree is set of nodes visible when tree is visited from Right side.

C++

// C++ program to print
// right view of a BST
#include <bits/stdc++.h>
using namespace std;
 
// Given Node node
struct node {
    int key;
    struct node *left, *right;
};
 
// 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;
}
 
// 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 node pointer
    return node;
}
 
// Function to print the right view
// of a binary tree.
void rightViewUtil(struct node* root,
                   int level,
                   int* max_level)
{
    // Base Case
    if (root == NULL)
        return;
 
    // If this is the last Node of its level
    if (*max_level < level) {
        cout <<"\t"<< root->key;
        *max_level = level;
    }
 
    // Recur for right subtree first,
    // then left subtree
    rightViewUtil(root->right, level + 1,
                  max_level);
 
    rightViewUtil(root->left, level + 1,
                  max_level);
}
 
// Wrapper over rightViewUtil()
void rightView(struct node* root)
{
    int max_level = 0;
    rightViewUtil(root, 1, &max_level);
}
 
// Driver Code
int main()
{
    /* Let us create following BST
              50
           /     \
          30      70
         /  \    /  \
       20   40  60   80
   */
    struct node* root = NULL;
 
    // Creating the BST
    root = insert(root, 50);
    insert(root, 30);
    insert(root, 20);
    insert(root, 40);
    insert(root, 70);
    insert(root, 60);
    insert(root, 80);
 
    // Function Call
    rightView(root);
 
    return 0;
}
 
// This code is contributed by shivanisinghss2110

                    

C

// C program to print
// right view of a BST
#include <stdio.h>
#include <stdlib.h>
 
// Given Node node
struct node {
    int key;
    struct node *left, *right;
};
 
// 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;
}
 
// 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 node pointer
    return node;
}
 
// Function to print the right view
// of a binary tree.
void rightViewUtil(struct node* root,
                   int level,
                   int* max_level)
{
    // Base Case
    if (root == NULL)
        return;
 
    // If this is the last Node of its level
    if (*max_level < level) {
        printf("%d\t", root->key);
        *max_level = level;
    }
 
    // Recur for right subtree first,
    // then left subtree
    rightViewUtil(root->right, level + 1,
                  max_level);
 
    rightViewUtil(root->left, level + 1,
                  max_level);
}
 
// Wrapper over rightViewUtil()
void rightView(struct node* root)
{
    int max_level = 0;
    rightViewUtil(root, 1, &max_level);
}
 
// Driver Code
int main()
{
    /* Let us create following BST
              50
           /     \
          30      70
         /  \    /  \
       20   40  60   80
   */
    struct node* root = NULL;
 
    // Creating the BST
    root = insert(root, 50);
    insert(root, 30);
    insert(root, 20);
    insert(root, 40);
    insert(root, 70);
    insert(root, 60);
    insert(root, 80);
 
    // Function Call
    rightView(root);
 
    return 0;
}

                    

Java

import java.io.*;
 
// Java program for Right view of BST
class GFG {
 
    // Given Node node
    static class node {
        int key;
        node left, right;
    };
 
    // 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;
    }
 
    // 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 node
        return node;
    }
 
    // Function to print the right view
    // of a binary tree.
    static void rightViewUtil(node root, int level,
                              int max_level)
    {
        // Base Case
        if (root == null)
            return;
 
        // If this is the last Node of its level
        if (max_level < level) {
            System.out.print(" " + root.key);
            max_level = level;
        }
 
        // Recur for right subtree
 
        rightViewUtil(root.right, level + 1, max_level);
    }
 
    // Wrapper over rightViewUtil()
    static void rightView(node root)
    {
        int max_level = 0;
        rightViewUtil(root, 1, max_level);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        /* Let us create following BST
                50
             /     \
            30      70
           /  \    /  \
         20   40  60   80
     */
        node root = null;
 
        // inserting value 50
        root = insert(root, 50);
 
        // inserting value 30
        insert(root, 30);
 
        // inserting value 20
        insert(root, 20);
 
        // inserting value 40
        insert(root, 40);
 
        // inserting value 70
        insert(root, 70);
 
        // inserting value 60
        insert(root, 60);
 
        // inserting value 80
        insert(root, 80);
 
        // print the BST
        rightView(root);
    }
}
// This code is contributed by abhijitjadhav1998

                    

Python3

# Python program to print right view of a BST
import sys
 
# Given Node node
class Node:
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None
 
# Function to insert a new node with
# given key in BST
def insert(node, key):
    # 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)
    else:
        node.right = insert(node.right, key)
 
    # Return the node pointer
    return node
 
# Function to print the right view
# of a binary tree.
def rightViewUtil(root, level, max_level):
    # Base Case
    if root is None:
        return
 
    # If this is the last Node of its level
    if (max_level[0] < level):
        print("\t", root.key, end="")
        max_level[0] = level
 
    # Recur for right subtree first,
    # then left subtree
    rightViewUtil(root.right, level + 1, max_level)
    rightViewUtil(root.left, level + 1, max_level)
 
# Wrapper over rightViewUtil()
def rightView(root):
    max_level = [0]
    rightViewUtil(root, 1, max_level)
 
# Driver Code
if __name__ == "__main__":
    # Let us create following BST
    #        50
    #     /     \
    #    30      70
    #   /  \    /  \
    #  20  40  60  80
 
    root = None
 
    # Creating the BST
    root = insert(root, 50)
    insert(root, 30)
    insert(root, 20)
    insert(root, 40)
    insert(root, 70)
    insert(root, 60)
    insert(root, 80)
 
    # Function Call
    rightView(root)
     
    #This code is contributed by japmeet01

                    

Output
    50    70    80

Time Complexity: O(N), where N is the number of nodes of the BST 
Auxiliary Space: O(1) 

  • Left view of BST: Left view of a Binary Search Tree is set of nodes visible when tree is visited from Left side.

C++

// C++ program to print
// left view of a BST
#include<bits/stdc++.h>
using namespace std;
 
// Given Node node
struct node {
    int key;
    struct node *left, *right;
};
 
// 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;
}
 
// 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 node pointer
    return node;
}
 
// Function to print left view of
// binary tree
void leftViewUtil(struct node* root,
                  int level,
                  int* max_level)
{
    // Base Case
    if (root == NULL)
        return;
 
    // If this is the first node
    // of its level
    if (*max_level < level) {
        cout <<"  "<< root->key;
        *max_level = level;
    }
 
    // Recur for left and right subtrees
    leftViewUtil(root->left, level + 1,
                 max_level);
 
    leftViewUtil(root->right, level + 1,
                 max_level);
}
 
// Wrapper over leftViewUtil()
void leftView(struct node* root)
{
    int max_level = 0;
    leftViewUtil(root, 1, &max_level);
}
 
// Driver Code
int main()
{
    /* Let us create following BST
              50
           /     \
          30      70
         /  \    /  \
       20   40  60   80
   */
    struct node* root = NULL;
 
    // Creating the BST
    root = insert(root, 50);
    insert(root, 30);
    insert(root, 20);
    insert(root, 40);
    insert(root, 70);
    insert(root, 60);
    insert(root, 80);
 
    // Function Call
    leftView(root);
 
    return 0;
}
 
// This code is contributed by shivanisinghss2110

                    

C

// C program to print
// left view of a BST
#include <stdio.h>
#include <stdlib.h>
 
// Given Node node
struct node {
    int key;
    struct node *left, *right;
};
 
// 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;
}
 
// 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 node pointer
    return node;
}
 
// Function to print left view of
// binary tree
void leftViewUtil(struct node* root,
                  int level,
                  int* max_level)
{
    // Base Case
    if (root == NULL)
        return;
 
    // If this is the first node
    // of its level
    if (*max_level < level) {
        printf("%d\t", root->key);
        *max_level = level;
    }
 
    // Recur for left and right subtrees
    leftViewUtil(root->left, level + 1,
                 max_level);
 
    leftViewUtil(root->right, level + 1,
                 max_level);
}
 
// Wrapper over leftViewUtil()
void leftView(struct node* root)
{
    int max_level = 0;
    leftViewUtil(root, 1, &max_level);
}
 
// Driver Code
int main()
{
    /* Let us create following BST
              50
           /     \
          30      70
         /  \    /  \
       20   40  60   80
   */
    struct node* root = NULL;
 
    // Creating the BST
    root = insert(root, 50);
    insert(root, 30);
    insert(root, 20);
    insert(root, 40);
    insert(root, 70);
    insert(root, 60);
    insert(root, 80);
 
    // Function Call
    leftView(root);
 
    return 0;
}

                    

Java

import java.io.*;
 
// Java program for Left view of BST
class GFG {
 
    // Given Node node
    static class node {
        int key;
        node left, right;
    };
 
    // 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;
    }
 
    // 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 node
        return node;
    }
 
    // Function to print left view of
    // binary tree
    static void leftViewUtil(node root, int level,
                             int max_level)
    {
        // Base Case
        if (root == null)
            return;
 
        // If this is the first node
        // of its level
        if (max_level < level) {
            System.out.print(" " + root.key);
            max_level = level;
        }
 
        // Recur for left
        leftViewUtil(root.left, level + 1, max_level);
        //leftViewUtil(root.right, level + 1, max_level);
    }
 
    // Wrapper over leftViewUtil()
    static void leftView(node root)
    {
        int max_level = 0;
        leftViewUtil(root, 1, max_level);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        /* Let us create following BST
                50
             /     \
            30      70
           /  \    /  \
         20   40  60   80
     */
        node root = null;
 
        // inserting value 50
        root = insert(root, 50);
 
        // inserting value 30
        insert(root, 30);
 
        // inserting value 20
        insert(root, 20);
 
        // inserting value 40
        insert(root, 40);
 
        // inserting value 70
        insert(root, 70);
 
        // inserting value 60
        insert(root, 60);
 
        // inserting value 80
        insert(root, 80);
 
        // print the BST
        leftView(root);
    }
}
// This code is contributed by abhijitjadhav1998

                    

Python3

# Python program to print
# left view of a BST
 
# Given Node node
 
 
class Node:
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None
 
# Function to insert a new node with
# given key in BST
 
 
def insert(node, key):
    # 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 node pointer
    return node
 
# Function to print left view of
# binary tree
 
 
def leftViewUtil(root, level, max_level):
    # Base Case
    if root is None:
        return
 
    # If this is the first node
    # of its level
    if max_level[0] < level:
        print(root.key, end=" ")
        max_level[0] = level
 
    # Recur for left and right subtrees
    leftViewUtil(root.left, level + 1, max_level)
    leftViewUtil(root.right, level + 1, max_level)
 
# Wrapper over leftViewUtil()
 
 
def leftView(root):
    max_level = [0]
    leftViewUtil(root, 1, max_level)
 
 
# Driver Code
if __name__ == '__main__':
    # Let us create following BST
    #          50
    #        /    \
    #      30      70
    #     /  \    /  \
    #   20   40  60   80
    root = None
 
    # Creating the BST
    root = insert(root, 50)
    insert(root, 30)
    insert(root, 20)
    insert(root, 40)
    insert(root, 70)
    insert(root, 60)
    insert(root, 80)
 
    # Function Call
    leftView(root)
     
    #This code is contributed by japmeet01

                    

Output
  50  30  20

Time Complexity: O(N), where N is the number of nodes of the BST 
Auxiliary Space: O(1) 

  • Height of BST: It is recursively calculated using height of left and right subtrees of the node and assigns height to the node as max of the heights of two children plus 1.

C++

// C++ program to print
// height of a BST
#include <bits/stdc++.h>
using namespace std;
 
// Given Node node
struct node
{
    int key;
    struct node *left, *right;
};
 
// 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;
}
 
// 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 node pointer
    return node;
}
 
// Returns height of the BST
int height(struct node* node)
{
    if (node == NULL)
        return 0;
    else
    {
         
        // Compute the depth of each subtree
        int lDepth = height(node->left);
        int rDepth = height(node->right);
 
        // Use the larger one
        if (lDepth > rDepth)
            return (lDepth + 1);
        else
            return (rDepth + 1);
    }
}
 
// Driver Code
int main()
{
     
    /* Let us create following BST
              50
           /     \
          30      70
         /  \    /  \
       20   40  60   80
   */
    struct node* root = NULL;
 
    // Creating the BST
    root = insert(root, 50);
    insert(root, 30);
    insert(root, 20);
    insert(root, 40);
    insert(root, 70);
    insert(root, 60);
    insert(root, 80);
 
    // Function Call
    cout << " " << height(root);
 
    return 0;
}
 
// This code is contributed by shivanisinghss2110

                    

C

// C program to print
// height of a BST
#include <stdio.h>
#include <stdlib.h>
 
// Given Node node
struct node {
    int key;
    struct node *left, *right;
};
 
// 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;
}
 
// 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 node pointer
    return node;
}
 
// Returns height of the BST
int height(struct node* node)
{
    if (node == NULL)
        return 0;
    else {
 
        // Compute the depth of each subtree
        int lDepth = height(node->left);
        int rDepth = height(node->right);
 
        // Use the larger one
        if (lDepth > rDepth)
            return (lDepth + 1);
        else
            return (rDepth + 1);
    }
}
 
// Driver Code
int main()
{
    /* Let us create following BST
              50
           /     \
          30      70
         /  \    /  \
       20   40  60   80
   */
    struct node* root = NULL;
 
    // Creating the BST
    root = insert(root, 50);
    insert(root, 30);
    insert(root, 20);
    insert(root, 40);
    insert(root, 70);
    insert(root, 60);
    insert(root, 80);
 
    // Function Call
    printf("%d", height(root));
 
    return 0;
}

                    

Java

import java.io.*;
 
// Java program for Height of BST
class GFG {
 
    // Given Node node
    static class node {
        int key;
        node left, right;
    };
 
    // 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;
    }
 
    // 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 node
        return node;
    }
 
    // Returns height of the BST
    static int height(node node)
    {
        if (node == null)
            return 0;
        else {
 
            // Compute the depth of each subtree
            int lDepth = height(node.left);
            int rDepth = height(node.right);
 
            // Use the larger one
            if (lDepth > rDepth)
                return (lDepth + 1);
            else
                return (rDepth + 1);
        }
    }
    // Driver Code
    public static void main(String[] args)
    {
 
        /* Let us create following BST
                50
             /     \
            30      70
           /  \    /  \
         20   40  60   80
     */
        node root = null;
 
        // inserting value 50
        root = insert(root, 50);
 
        // inserting value 30
        insert(root, 30);
 
        // inserting value 20
        insert(root, 20);
 
        // inserting value 40
        insert(root, 40);
 
        // inserting value 70
        insert(root, 70);
 
        // inserting value 60
        insert(root, 60);
 
        // inserting value 80
        insert(root, 80);
 
        // Function Call
        System.out.println(" " + height(root));
    }
}
// This code is contributed by abhijitjadhav1998

                    

Python3

# Python program to print
# height of a BST
import sys
 
# Given Node node
class Node:
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None
 
# Function to insert a new node with
# given key in BST
def insert(root, key):
    # If the tree is empty, return a new node
    if root is None:
        return Node(key)
 
    # Otherwise, recur down the tree
    if key < root.key:
        root.left = insert(root.left, key)
    elif key > root.key:
        root.right = insert(root.right, key)
 
    # Return the node pointer
    return root
 
# Returns height of the BST
def height(node):
    if node is None:
        return 0
    else:
        # Compute the depth of each subtree
        lDepth = height(node.left)
        rDepth = height(node.right)
 
        # Use the larger one
        if lDepth > rDepth:
            return lDepth + 1
        else:
            return rDepth + 1
 
# Driver Code
if __name__ == '__main__':
    # Let us create following BST
    #           50
    #        /      \
    #       30       70
    #      /  \     /  \
    #    20   40   60   80
    root = None
 
    # Creating the BST
    root = insert(root, 50)
    insert(root, 30)
    insert(root, 20)
    insert(root, 40)
    insert(root, 70)
    insert(root, 60)
    insert(root, 80)
 
    # Function Call
    print(' ', height(root))
     
    #This code is contributed by japmeet01

                    

Output
 3

Time Complexity: O(N), where N is the number of nodes of the BST 
Auxiliary Space: O(1) 

  • Delete a Node of BST: It is used to delete a node with specific key from the BST and return the new BST.

Different scenarios for deleting the node:

  1. Node to be deleted is the leaf node : Its simple you can just null it out.
  2. Node to be deleted has one child : You can just replace the node with the child node.
  3. Node to be deleted has two child :
  • Need to figure out what will be the replacement of the node to be deleted.
  • Want minimal disruption to the existing tree structure
  • Can table the replacement node from the deleted nodes left or right subtree.
  • If taking if from the left subtree, we have to take the largest value in the left subtree.
  • If taking if from the right subtree, we have to take the smallest value in the right subtree.
  • Choose one approach and stick to it. 

C++

// C++ program to delete
// a node of BST
#include <bits/stdc++.h>
using namespace std;
 
// Given Node node
struct node {
    int key;
    struct node *left, *right;
};
 
// 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;
}
 
// 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 node pointer
    return node;
}
 
// Function to do inorder traversal of BST
void inorder(struct node* root)
{
    if (root != NULL) {
        inorder(root->left);
        cout <<" "<< root->key;
        inorder(root->right);
    }
}
 
// Function that returns the node with minimum
// key value found in that tree
struct node* minValueNode(struct node* node)
{
    struct node* current = node;
 
    // Loop down to find the leftmost leaf
    while (current && current->left != NULL)
        current = current->left;
 
    return current;
}
 
// Function that deletes the key and
// returns the new root
struct node* deleteNode(struct node* root,
                        int key)
{
    // base Case
    if (root == NULL)
        return root;
 
    // If the key to be deleted is
    // smaller than the root's key,
    // then it lies in left subtree
    if (key < root->key) {
        root->left
            = deleteNode(root->left, key);
    }
 
    // If the key to be deleted is
    // greater than the root's key,
    // then it lies in right subtree
    else if (key > root->key) {
 
        root->right
            = deleteNode(root->right, key);
    }
 
    // If key is same as root's key,
    // then this is the node
    // to be deleted
    else {
 
        // Node with only one child
        // or no child
        if (root->left == NULL) {
            struct node* temp = root->right;
            free(root);
            return temp;
        }
        else if (root->right == NULL) {
            struct node* temp = root->left;
            free(root);
            return temp;
        }
 
        // Node with two children:
        // Get the inorder successor(smallest
        // in the right subtree)
        struct node* temp = minValueNode(root->right);
 
        // Copy the inorder successor's
        // content to this node
        root->key = temp->key;
 
        // Delete the inorder successor
        root->right
            = deleteNode(root->right, temp->key);
    }
    return root;
}
 
// Driver Code
int main()
{
    /* Let us create following BST
              50
           /     \
          30      70
         /  \    /  \
       20   40  60   80
   */
    struct node* root = NULL;
 
    // Creating the BST
    root = insert(root, 50);
    insert(root, 30);
    insert(root, 20);
    insert(root, 40);
    insert(root, 70);
    insert(root, 60);
    insert(root, 80);
 
    // Function Call
    root = deleteNode(root, 60);
    inorder(root);
 
    return 0;
}
 
// This code is contributed by shivanisinghss2110

                    

C

// C program to delete
// a node of BST
#include <stdio.h>
#include <stdlib.h>
 
// Given Node node
struct node {
    int key;
    struct node *left, *right;
};
 
// 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;
}
 
// 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 node pointer
    return node;
}
 
// Function to do inorder traversal of BST
void inorder(struct node* root)
{
    if (root != NULL) {
        inorder(root->left);
        printf("%d ", root->key);
        inorder(root->right);
    }
}
 
// Function that returns the node with minimum
// key value found in that tree
struct node* minValueNode(struct node* node)
{
    struct node* current = node;
 
    // Loop down to find the leftmost leaf
    while (current && current->left != NULL)
        current = current->left;
 
    return current;
}
 
// Function that deletes the key and
// returns the new root
struct node* deleteNode(struct node* root,
                        int key)
{
    // base Case
    if (root == NULL)
        return root;
 
    // If the key to be deleted is
    // smaller than the root's key,
    // then it lies in left subtree
    if (key < root->key) {
        root->left
            = deleteNode(root->left, key);
    }
 
    // If the key to be deleted is
    // greater than the root's key,
    // then it lies in right subtree
    else if (key > root->key) {
 
        root->right
            = deleteNode(root->right, key);
    }
 
    // If key is same as root's key,
    // then this is the node
    // to be deleted
    else {
 
        // Node with only one child
        // or no child
        if (root->left == NULL) {
            struct node* temp = root->right;
            free(root);
            return temp;
        }
        else if (root->right == NULL) {
            struct node* temp = root->left;
            free(root);
            return temp;
        }
 
        // Node with two children:
        // Get the inorder successor(smallest
        // in the right subtree)
        struct node* temp = minValueNode(root->right);
 
        // Copy the inorder successor's
        // content to this node
        root->key = temp->key;
 
        // Delete the inorder successor
        root->right
            = deleteNode(root->right, temp->key);
    }
    return root;
}
 
// Driver Code
int main()
{
    /* Let us create following BST
              50
           /     \
          30      70
         /  \    /  \
       20   40  60   80
   */
    struct node* root = NULL;
 
    // Creating the BST
    root = insert(root, 50);
    insert(root, 30);
    insert(root, 20);
    insert(root, 40);
    insert(root, 70);
    insert(root, 60);
    insert(root, 80);
 
    // Function Call
    root = deleteNode(root, 60);
    inorder(root);
 
    return 0;
}

                    

Java

import java.io.*;
 
// Java program for Delete a Node of BST
class GFG {
 
    // Given Node node
    static class node {
        int key;
        node left, right;
    };
 
    // 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;
    }
 
    // 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 node
        return node;
    }
 
    // Function to do inorder traversal of BST
    static void inorder(node root)
    {
        if (root != null) {
            inorder(root.left);
            System.out.print(" " + root.key);
            inorder(root.right);
        }
    }
    // Function that returns the node with minimum
    // key value found in that tree
    static node minValueNode(node node)
    {
        node current = node;
 
        // Loop down to find the leftmost leaf
        while (current != null && current.left != null)
            current = current.left;
 
        return current;
    }
 
    // Function that deletes the key and
    // returns the new root
    static node deleteNode(node root, int key)
    {
        // base Case
        if (root == null)
            return root;
 
        // If the key to be deleted is
        // smaller than the root's key,
        // then it lies in left subtree
        if (key < root.key) {
            root.left = deleteNode(root.left, key);
        }
 
        // If the key to be deleted is
        // greater than the root's key,
        // then it lies in right subtree
        else if (key > root.key) {
 
            root.right = deleteNode(root.right, key);
        }
 
        // If key is same as root's key,
        // then this is the node
        // to be deleted
        else {
 
            // Node with only one child
            // or no child
            if (root.left == null) {
                node temp = root.right;
                return temp;
            }
            else if (root.right == null) {
                node temp = root.left;
                return temp;
            }
 
            // Node with two children:
            // Get the inorder successor(smallest
            // in the right subtree)
            node temp = minValueNode(root.right);
 
            // Copy the inorder successor's
            // content to this node
            root.key = temp.key;
 
            // Delete the inorder successor
            root.right = deleteNode(root.right, temp.key);
        }
        return root;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        /* Let us create following BST
                50
             /     \
            30      70
           /  \    /  \
         20   40  60   80
     */
        node root = null;
 
        // inserting value 50
        root = insert(root, 50);
 
        // inserting value 30
        insert(root, 30);
 
        // inserting value 20
        insert(root, 20);
 
        // inserting value 40
        insert(root, 40);
 
        // inserting value 70
        insert(root, 70);
 
        // inserting value 60
        insert(root, 60);
 
        // inserting value 80
        insert(root, 80);
 
        // Function Call
        root = deleteNode(root, 60);
        inorder(root);
    }
}
// This code is contributed by abhijitjadhav1998

                    

Python3

# Python program to delete a node of BST
 
# Given Node node
class Node:
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None
 
# Function to insert a new node with
# given key in BST
def insert(root, key):
    # If the tree is empty, return a new node
    if root is None:
        return Node(key)
 
    # Otherwise, recur down the tree
    if key < root.key:
        root.left = insert(root.left, key)
    elif key > root.key:
        root.right = insert(root.right, key)
 
    # Return the node pointer
    return root
 
# Function to do inorder traversal of BST
def inorder(root):
    if root:
        inorder(root.left)
        print(root.key, end=" ")
        inorder(root.right)
 
# Function that returns the node with minimum
# key value found in that tree
def minValueNode(node):
    current = node
 
    # Loop down to find the leftmost leaf
    while current and current.left is not None:
        current = current.left
 
    return c