Introduction to Binary Search Tree
Last Updated :
14 Aug, 2024
Binary Search Tree is a data structure used in computer science for organizing and storing data in a sorted manner. Binary search tree follows all properties of binary tree and its left child contains values less than the parent node and the right child contains values greater than the parent node. This hierarchical structure allows for efficient Searching, Insertion, and Deletion operations on the data stored in the tree.

Binary Search Tree
What is Binary Search Tree?
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.
Properties of Binary Search Tree:
- 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.
- 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).
Searching in BST means to locate a specific node in the data structure. In Binary search tree, searching a node is easy because of its a specific order. The steps of searching a node in Binary Search tree are listed as follows –
- First, compare the element to be searched with the root element of the tree.
- If root is matched with the target element, then return the node’s location.
- If it is not matched, then check whether the item is less than the root element, if it is smaller than the root element, then move to the left subtree.
- If it is larger than the root element, then move to the right subtree.
- Repeat the above procedure recursively until the match is found.
- If the element is not found or not present in the tree, then return NULL.
Now, let’s understand the searching in binary tree using an example:
Below is given a BST and we have to search for element 6.
Below is the implementation of searching in BST:
C++
#include <iostream>
using namespace std;
struct Node {
int key;
Node* left;
Node* right;
Node(int item) {
key = item;
left = right = NULL;
}
};
// function to search a key in a BST
Node* search(Node* root, int key) {
// Base Cases: root is null or key
// is present at root
if (root == NULL || root->key == key)
return root;
// Key is greater than root's key
if (root->key < key)
return search(root->right, key);
// Key is smaller than root's key
return search(root->left, key);
}
// Driver Code
int main() {
// Creating a hard coded tree for keeping
// the length of the code small. We need
// to make sure that BST properties are
// maintained if we try some other cases.
Node* root = new Node(50);
root->left = new Node(30);
root->right = new Node(70);
root->left->left = new Node(20);
root->left->right = new Node(40);
root->right->left = new Node(60);
root->right->right = new Node(80);
(search(root, 19) != NULL)? cout << "Found\n":
cout << "Not Found\n";
(search(root, 80) != NULL)? cout << "Found\n":
cout << "Not Found\n";
return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
struct Node {
int key;
struct Node* left;
struct Node* right;
};
// Constructor 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 search a key in a BST
struct Node* search(struct Node* root, int key)
{
// Base Cases: root is null or key is
// present at root
if (root == NULL || root->key == key)
return root;
// Key is greater than root's key
if (root->key < key)
return search(root->right, key);
// Key is smaller than root's key
return search(root->left, key);
}
// Driver Code
int main()
{
// Creating a hard coded tree for keeping
// the length of the code small. We need
// to make sure that BST properties are
// maintained if we try some other cases.
struct Node* root = newNode(50);
root->left = newNode(30);
root->right = newNode(70);
root->left->left = newNode(20);
root->left->right = newNode(40);
root->right->left = newNode(60);
root->right->right = newNode(80);
printf(search(root, 19) != NULL ? "Found\n"
: "Not Found\n");
printf(search(root, 80) != NULL ? "Found\n"
: "Not Found\n");
return 0;
}
Java
class Node {
int key;
Node left, right;
public Node(int item)
{
key = item;
left = right = null;
}
}
class GfG {
// function to search a key in a BST
static Node search(Node root, int key)
{
// Base Cases: root is null or key is present at
// root
if (root == null || root.key == key)
return root;
// Key is greater than root's key
if (root.key < key)
return search(root.right, key);
// Key is smaller than root's key
return search(root.left, key);
}
public static void main(String[] args)
{
// Creating a hard coded tree for keeping
// the length of the code small. We need
// to make sure that BST properties are
// maintained if we try some other cases.
Node root = new Node(50);
root.left = new Node(30);
root.right = new Node(70);
root.left.left = new Node(20);
root.left.right = new Node(40);
root.right.left = new Node(60);
root.right.right = new Node(80);
// Searching for keys in the BST
System.out.println(search(root, 19) != null
? "Found"
: "Not Found");
System.out.println(search(root, 80) != null
? "Found"
: "Not Found");
}
}
Python
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
# function to search a key in a BST
def search(root, key):
# Base Cases: root is null or key
# is present at root
if root is None or root.key == key:
return root
# Key is greater than root's key
if root.key < key:
return search(root.right, key)
# Key is smaller than root's key
return search(root.left, key)
# Creating a hard coded tree for keeping
# the length of the code small. We need
# to make sure that BST properties are
# maintained if we try some other cases.
root = Node(50)
root.left = Node(30)
root.right = Node(70)
root.left.left = Node(20)
root.left.right = Node(40)
root.right.left = Node(60)
root.right.right = Node(80)
# Searching for keys in the BST
print("Found" if search(root, 19) else "Not Found")
print("Found" if search(root, 80) else "Not Found")
C#
using System;
public class Node
{
public int Key;
public Node Left, Right;
public Node(int item)
{
Key = item;
Left = Right = null;
}
}
public class GfG
{
// function to search a key in a BST
public static Node Search(Node root, int key)
{
// Base Cases: root is null or key is
// present at root
if (root == null || root.Key == key)
return root;
// Key is greater than root's key
if (root.Key < key)
return Search(root.Right, key);
// Key is smaller than root's key
return Search(root.Left, key);
}
// Driver Code
public static void Main()
{
// Creating a hard coded tree for keeping
// the length of the code small. We need
// to make sure that BST properties are
// maintained if we try some other cases.
Node root = new Node(50);
root.Left = new Node(30);
root.Right = new Node(70);
root.Left.Left = new Node(20);
root.Left.Right = new Node(40);
root.Right.Left = new Node(60);
root.Right.Right = new Node(80);
// Searching for keys in the BST
Console.WriteLine(Search(root, 19) != null ?
"Found" : "Not Found");
Console.WriteLine(Search(root, 80) != null ?
"Found" : "Not Found");
}
}
JavaScript
class Node {
constructor(key)
{
this.key = key;
this.left = null;
this.right = null;
}
}
// function to search a key in a BST
function search(root, key)
{
// Base Cases: root is null or key is
// present at root
if (root === null || root.key === key)
return root;
// Key is greater than root's key
if (root.key < key)
return search(root.right, key);
// Key is smaller than root's key
return search(root.left, key);
}
// Creating a hard coded tree for keeping
// the length of the code small. We need
// to make sure that BST properties are
// maintained if we try some other cases.
let root = new Node(50);
root.left = new Node(30);
root.right = new Node(70);
root.left.left = new Node(20);
root.left.right = new Node(40);
root.right.left = new Node(60);
root.right.right = new Node(80);
// Searching for keys in the BST
console.log(search(root, 19) !== null ? "Found"
: "Not Found");
console.log(search(root, 80) !== null ? "Found"
: "Not Found");
Time Complexity : O(h) where h is height of 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.
Below is the implementation of the Insertion of a single node in Binary Search Tree:
C++
#include <iostream>
using namespace std;
struct Node {
int key;
Node* left;
Node* right;
Node(int item) {
key = item;
left = NULL;
right = NULL;
}
};
// A utility function to insert a new node with
// the given key
Node* insert(Node* node, int key) {
// If the tree is empty, return a new node
if (node == NULL)
return new Node(key);
// If the key is already present in the tree,
// return the node
if (node->key == key)
return node;
// Otherwise, recur down the tree/ If the key
// to be inserted is greater than the node's key,
// insert it in the right subtree
if (node->key < key)
node->right = insert(node->right, key);
// If the key to be inserted is smaller than
// the node's key,insert it in the left subtree
else
node->left = insert(node->left, key);
// Return the (unchanged) node pointer
return node;
}
// A utility function to do inorder tree traversal
void inorder(Node* root) {
if (root != NULL) {
inorder(root->left);
cout << root->key << " ";
inorder(root->right);
}
}
// Driver program to test the above functions
int main() {
// Creating the following BST
// 50
// / \
// 30 70
// / \ / \
// 20 40 60 80
Node* root = new Node(50);
root = insert(root, 30);
root = insert(root, 20);
root = insert(root, 40);
root = insert(root, 70);
root = insert(root, 60);
root = insert(root, 80);
// Print inorder traversal of the BST
inorder(root);
return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
// Define the structure for a BST node
struct Node {
int key;
struct Node* left;
struct Node* 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 the given key
struct Node* insert(struct Node* node, int key) {
// If the tree is empty, return a new node
if (node == NULL)
return newNode(key);
// If the key is already present in the tree,
// return the node
if (node->key == key)
return node;
// Otherwise, recur down the tree. If the key
// to be inserted is greater than the node's key,
// insert it in the right subtree
if (node->key < key)
node->right = insert(node->right, key);
// If the key to be inserted is smaller than
// the node's key,insert it in the left subtree
else
node->left = insert(node->left, key);
// Return the (unchanged) node pointer
return node;
}
// Function to perform inorder tree traversal
void inorder(struct Node* root) {
if (root != NULL) {
inorder(root->left);
printf("%d ", root->key);
inorder(root->right);
}
}
// Driver program to test the above functions
int main() {
// Creating the following BST
// 50
// / \
// 30 70
// / \ / \
// 20 40 60 80
struct Node* root = newNode(50);
root = insert(root, 30);
root = insert(root, 20);
root = insert(root, 40);
root = insert(root, 70);
root = insert(root, 60);
root = insert(root, 80);
// Print inorder traversal of the BST
inorder(root);
return 0;
}
Java
class Node {
int key;
Node left, right;
public Node(int item)
{
key = item;
left = right = null;
}
}
class GfG {
// A utility function to insert a new node
// with the given key
static Node insert(Node root, int key)
{
// If the tree is empty, return a new node
if (root == null)
return new Node(key);
// If the key is already present in the tree,
// return the node
if (root.key == key)
return root;
// Otherwise, recur down the tree
if (key < root.key)
root.left = insert(root.left, key);
else
root.right = insert(root.right, key);
// Return the (unchanged) node pointer
return root;
}
// A utility function to do inorder tree traversal
static void inorder(Node root)
{
if (root != null) {
inorder(root.left);
System.out.print(root.key + " ");
inorder(root.right);
}
}
// Driver method
public static void main(String[] args)
{
Node root = null;
// Creating the following BST
// 50
// / \
// 30 70
// / \ / \
// 20 40 60 80
root = insert(root, 50);
root = insert(root, 30);
root = insert(root, 20);
root = insert(root, 40);
root = insert(root, 70);
root = insert(root, 60);
root = insert(root, 80);
// Print inorder traversal of the BST
inorder(root);
}
}
Python
# Python program to demonstrate
# insert operation in binary search tree
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
# A utility function to insert
# a new node with the given key
def insert(root, key):
if root is None:
return Node(key)
if root.val == key:
return root
if root.val < key:
root.right = insert(root.right, key)
else:
root.left = insert(root.left, key)
return root
# A utility function to do inorder tree traversal
def inorder(root):
if root:
inorder(root.left)
print(root.val, end=" ")
inorder(root.right)
# Creating the following BST
# 50
# / \
# 30 70
# / \ / \
# 20 40 60 80
r = Node(50)
r = insert(r, 30)
r = insert(r, 20)
r = insert(r, 40)
r = insert(r, 70)
r = insert(r, 60)
r = insert(r, 80)
# Print inorder traversal of the BST
inorder(r)
C#
using System;
class Node {
public int key;
public Node left, right;
public Node(int item) {
key = item;
left = right = null;
}
}
class GfG {
// A function to insert a new node with the given key
public static Node Insert(Node node, int key) {
if (node == null)
return new Node(key);
// Duplicates not allowed
if (key == node.key)
return node;
if (key < node.key)
node.left = Insert(node.left, key);
else if (key > node.key)
node.right = Insert(node.right, key);
return node;
}
// A utility function to do inorder tree traversal
public static void Inorder(Node root) {
if (root != null) {
Inorder(root.left);
Console.Write(root.key + " ");
Inorder(root.right);
}
}
// Driver method
public static void Main() {
// Creating the following BST
// 50
// / \
// 30 70
// / \ / \
// 20 40 60 80
Node root = new Node(50);
root = Insert(root, 30);
root = Insert(root, 20);
root = Insert(root, 40);
root = Insert(root, 70);
root = Insert(root, 60);
root = Insert(root, 80);
// Print inorder traversal of the BST
Inorder(root);
}
}
JavaScript
class Node {
constructor(key) {
this.key = key;
this.left = null;
this.right = null;
}
}
// A utility function to insert a new
// node with the given key
function insert(root, key) {
if (root === null)
return new Node(key);
// Duplicates not allowed
if (root.key === key)
return root;
if (key < root.key)
root.left = insert(root.left, key);
else if (key > root.key)
root.right = insert(root.right, key);
return root;
}
// A utility function to do inorder
// tree traversal
function inorder(root) {
if (root !== null) {
inorder(root.left);
console.log(root.key + " ");
inorder(root.right);
}
}
// Creating the following BST
// 50
// / \
// 30 70
// / \ / \
// 20 40 60 80
let root = new Node(50);
root = insert(root, 30);
root = insert(root, 20);
root = insert(root, 40);
root = insert(root, 70);
root = insert(root, 60);
root = insert(root, 80);
// Print inorder traversal of the BST
inorder(root);
Output20 30 40 50 60 70 80
Time Complexity : O(h) where h is height 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:
Node to be deleted is the leaf node :
Its simple you can just null it out.

Node to be deleted has one child :
You can just replace the node with the child node.

Node to be deleted has two children :
Here we have to delete the node is such a way, that the resulting tree follows the properties of a BST.  The trick is to find the inorder successor of the node. Copy contents of the inorder successor to the node, and delete the inorder successor.

Take Care of following things while deleting a node of a BST:
- Need to figure out what will be the replacement of the node to be deleted.
- Want minimal disruption to the existing tree structure
- Can take 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.
Below is the implementation of the deletion in BST:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int key;
Node* left;
Node* right;
Node(int k)
{
key = k;
left = right = NULL;
}
};
// Note that it is not a generic inorder
// successor function. It mainly works
// when right child is not empty which is
// the case wwe need in BST delete
Node* getSuccessor(Node* curr)
{
curr = curr->right;
while (curr != NULL && curr->left != NULL)
curr = curr->left;
return curr;
}
// This function deletes a given key x from
// the give BST and returns modified root of
// the BST (if it is modified)
Node* delNode(Node* root, int x)
{
// Base case
if (root == NULL)
return root;
// If key to be searched is in a subtree
if (root->key > x)
root->left = delNode(root->left, x);
else if (root->key < x)
root->right = delNode(root->right, x);
// If root matches with the given key
else {
// Cases when root has 0 children
// or only right child
if (root->left == NULL) {
Node* temp = root->right;
delete root;
return temp;
}
// When root has only left child
if (root->right == NULL) {
Node* temp = root->left;
delete root;
return temp;
}
// When both children are present
Node* succ = getSuccessor(root);
root->key = succ->key;
root->right = delNode(root->right, succ->key);
}
return root;
}
// Utility function to do inorder
// traversal
void inorder(Node* root)
{
if (root != NULL) {
inorder(root->left);
cout << root->key << " ";
inorder(root->right);
}
}
// Driver code
int main()
{
Node* root = new Node(10);
root->left = new Node(5);
root->right = new Node(15);
root->right->left = new Node(12);
root->right->right = new Node(18);
int x = 15;
root = delNode(root, x);
inorder(root);
return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
struct Node {
int key;
struct Node* left;
struct Node* right;
};
// Note that it is not a generic inorder successor
// function. It mainly works when the right child
// is not empty, which is the case we need in
// BST delete.
struct Node* getSuccessor(struct Node* curr) {
curr = curr->right;
while (curr != NULL && curr->left != NULL)
curr = curr->left;
return curr;
}
// This function deletes a given key x from the
// given BST and returns the modified root of
// the BST (if it is modified)
struct Node* delNode(struct Node* root, int x) {
// Base case
if (root == NULL)
return root;
// If key to be searched is in a subtree
if (root->key > x)
root->left = delNode(root->left, x);
else if (root->key < x)
root->right = delNode(root->right, x);
else {
// If root matches with the given key
// Cases when root has 0 children or only right child
if (root->left == NULL) {
struct Node* temp = root->right;
free(root);
return temp;
}
// When root has only left child
if (root->right == NULL) {
struct Node* temp = root->left;
free(root);
return temp;
}
// When both children are present
struct Node* succ = getSuccessor(root);
root->key = succ->key;
root->right = delNode(root->right, succ->key);
}
return root;
}
struct Node* createNode(int key) {
struct Node* newNode =
(struct Node*)malloc(sizeof(struct Node));
newNode->key = key;
newNode->left = newNode->right = NULL;
return newNode;
}
// Utility function to do inorder traversal
void inorder(struct Node* root) {
if (root != NULL) {
inorder(root->left);
printf("%d ", root->key);
inorder(root->right);
}
}
// Driver code
int main() {
struct Node* root = createNode(10);
root->left = createNode(5);
root->right = createNode(15);
root->right->left = createNode(12);
root->right->right = createNode(18);
int x = 15;
root = delNode(root, x);
inorder(root);
return 0;
}
Java
class Node {
int key;
Node left, right;
public Node(int item) {
key = item;
left = right = null;
}
}
class GfG {
// This function deletes a given key x from the
// given BST and returns the modified root of
// the BST (if it is modified).
static Node delNode(Node root, int x) {
// Base case
if (root == null) {
return root;
}
// If key to be searched is in a subtree
if (root.key > x) {
root.left = delNode(root.left, x);
} else if (root.key < x) {
root.right = delNode(root.right, x);
} else {
// If root matches with the given key
// Cases when root has 0 children or
// only right child
if (root.left == null) {
return root.right;
}
// When root has only left child
if (root.right == null) {
return root.left;
}
// When both children are present
Node succ = getSuccessor(root);
root.key = succ.key;
root.right = delNode(root.right, succ.key);
}
return root;
}
// Note that it is not a generic inorder successor
// function. It mainly works when the right child
// is not empty, which is the case we need in BST
// delete.
static Node getSuccessor(Node curr) {
curr = curr.right;
while (curr != null && curr.left != null) {
curr = curr.left;
}
return curr;
}
// Utility function to do inorder traversal
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) {
Node root = new Node(10);
root.left = new Node(5);
root.right = new Node(15);
root.right.left = new Node(12);
root.right.right = new Node(18);
int x = 15;
root = delNode(root, x);
inorder(root);
}
}
Python
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
# Note that it is not a generic inorder successor
# function. It mainly works when the right child
# is not empty, which is the case we need in BST
# delete.
def get_successor(curr):
curr = curr.right
while curr is not None and curr.left is not None:
curr = curr.left
return curr
# This function deletes a given key x from the
# given BST and returns the modified root of the
# BST (if it is modified).
def del_node(root, x):
# Base case
if root is None:
return root
# If key to be searched is in a subtree
if root.key > x:
root.left = del_node(root.left, x)
elif root.key < x:
root.right = del_node(root.right, x)
else:
# If root matches with the given key
# Cases when root has 0 children or
# only right child
if root.left is None:
return root.right
# When root has only left child
if root.right is None:
return root.left
# When both children are present
succ = get_successor(root)
root.key = succ.key
root.right = del_node(root.right, succ.key)
return root
# Utility function to do inorder traversal
def inorder(root):
if root is not None:
inorder(root.left)
print(root.key, end=" ")
inorder(root.right)
# Driver code
if __name__ == "__main__":
root = Node(10)
root.left = Node(5)
root.right = Node(15)
root.right.left = Node(12)
root.right.right = Node(18)
x = 15
root = del_node(root, x)
inorder(root)
print()
C#
using System;
class Node {
public int key;
public Node left, right;
public Node(int item) {
key = item;
left = right = null;
}
}
class GfG {
// This function deletes a given key x from the
// given BST and returns the modified root of
// the BST (if it is modified).
public static Node DelNode(Node root, int x) {
// Base case
if (root == null) {
return root;
}
// If key to be searched is in a subtree
if (root.key > x) {
root.left = DelNode(root.left, x);
} else if (root.key < x) {
root.right = DelNode(root.right, x);
} else {
// If root matches with the given key
// Cases when root has 0 children or
// only right child
if (root.left == null) {
return root.right;
}
// When root has only left child
if (root.right == null) {
return root.left;
}
// When both children are present
Node succ = GetSuccessor(root);
root.key = succ.key;
root.right = DelNode(root.right, succ.key);
}
return root;
}
// Note that it is not a generic inorder successor
// function. It mainly works when the right child
// is not empty, which is the case we need in BST
// delete.
public static Node GetSuccessor(Node curr) {
curr = curr.right;
while (curr != null && curr.left != null) {
curr = curr.left;
}
return curr;
}
// Utility function to do inorder traversal
public static void Inorder(Node root) {
if (root != null) {
Inorder(root.left);
Console.Write(root.key + " ");
Inorder(root.right);
}
}
// Driver code
public static void Main(string[] args) {
Node root = new Node(10);
root.left = new Node(5);
root.right = new Node(15);
root.right.left = new Node(12);
root.right.right = new Node(18);
int x = 15;
root = DelNode(root, x);
Inorder(root);
}
}
JavaScript
class Node {
constructor(key) {
this.key = key;
this.left = null;
this.right = null;
}
}
// Note that it is not a generic inorder successor
// function. It mainly works when the right child
// is not empty, which is the case we need in BST
// delete.
function getSuccessor(curr) {
curr = curr.right;
while (curr !== null && curr.left !== null) {
curr = curr.left;
}
return curr;
}
// This function deletes a given key x from the
// given BST and returns the modified root of the
// BST (if it is modified).
function delNode(root, x) {
// Base case
if (root === null) {
return root;
}
// If key to be searched is in a subtree
if (root.key > x) {
root.left = delNode(root.left, x);
} else if (root.key < x) {
root.right = delNode(root.right, x);
} else {
// If root matches with the given key
// Cases when root has 0 children or
// only right child
if (root.left === null)
return root.right;
// When root has only left child
if (root.right === null)
return root.left;
// When both children are present
let succ = getSuccessor(root);
root.key = succ.key;
root.right = delNode(root.right, succ.key);
}
return root;
}
// Utility function to do inorder traversal
function inorder(root) {
if (root !== null) {
inorder(root.left);
console.log(root.key + " ");
inorder(root.right);
}
}
// Driver code
let root = new Node(10);
root.left = new Node(5);
root.right = new Node(15);
root.right.left = new Node(12);
root.right.right = new Node(18);
let x = 15;
root = delNode(root, x);
inorder(root);
console.log();
Time Complexity : O(h) where h is height of BST
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.
Below is the implementation of how to do inorder traversal of a Binary Search Tree:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int key;
Node* left;
Node* right;
Node(int k)
{
key = k;
left = right = NULL;
}
};
// Utility function to do inorder
// traversal
void inorder(Node* root)
{
if (root != NULL) {
inorder(root->left);
cout << root->key << " ";
inorder(root->right);
}
}
// Driver code
int main()
{
Node* root = new Node(10);
root->left = new Node(5);
root->right = new Node(15);
root->right->left = new Node(12);
root->right->right = new Node(18);
inorder(root);
return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
struct Node {
int key;
struct Node* left;
struct Node* right;
};
// Utility function to do inorder traversal
void inorder(struct Node* root) {
if (root != NULL) {
inorder(root->left);
printf("%d ", root->key);
inorder(root->right);
}
}
struct Node* createNode(int key) {
struct Node* newNode =
(struct Node*)malloc(sizeof(struct Node));
newNode->key = key;
newNode->left = newNode->right = NULL;
return newNode;
}
// Driver code
int main() {
struct Node* root = createNode(10);
root->left = createNode(5);
root->right = createNode(15);
root->right->left = createNode(12);
root->right->right = createNode(18);
inorder(root);
return 0;
}
Java
class Node {
int key;
Node left, right;
public Node(int item) {
key = item;
left = right = null;
}
}
class GfG {
// Utility function to do inorder traversal
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) {
Node root = new Node(10);
root.left = new Node(5);
root.right = new Node(15);
root.right.left = new Node(12);
root.right.right = new Node(18);
inorder(root);
}
}
Python
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
# Utility function to do inorder traversal
def inorder(root):
if root is not None:
inorder(root.left)
print(root.key, end=" ")
inorder(root.right)
# Driver code
if __name__ == "__main__":
root = Node(10)
root.left = Node(5)
root.right = Node(15)
root.right.left = Node(12)
root.right.right = Node(18)
inorder(root)
print()
C#
using System;
class Node {
public int key;
public Node left, right;
public Node(int item) {
key = item;
left = right = null;
}
}
class GfG {
// Utility function to do inorder traversal
public static void Inorder(Node root) {
if (root != null) {
Inorder(root.left);
Console.Write(root.key + " ");
Inorder(root.right);
}
}
// Driver code
public static void Main(string[] args) {
Node root = new Node(10);
root.left = new Node(5);
root.right = new Node(15);
root.right.left = new Node(12);
root.right.right = new Node(18);
Inorder(root);
}
}
JavaScript
class Node {
constructor(key) {
this.key = key;
this.left = null;
this.right = null;
}
}
// Utility function to do inorder traversal
function inorder(root) {
if (root !== null) {
inorder(root.left);
console.log(root.key + " ");
inorder(root.right);
}
}
// Driver code
let root = new Node(10);
root.left = new Node(5);
root.right = new Node(15);
root.right.left = new Node(12);
root.right.right = new Node(18);
inorder(root);
Time Complexity: O(N), where N is the number of nodes of the BSTÂ
Applications of BST:
- Self-balancing binary search tree: Self-balancing data structures such as AVL tree and Red-black tree are the most useful variations of BSTs. In these variations, we maintain the height as O(Log n) so that all operations are bounded by O(Log n). TreeSet and TreeMap in Java (or set and map in C++) are library implementations of self balancing BSTs.
- Sorted Stream of Data : If we wish to maintain a sorted stream of data where we wish to have operations like insert, search, delete and traversal in sorted order, BST is the most suitable data structure for this case.
- Doubly Ended Priority Queues: With Self Balancing BSTs, we can extract both maximum and minimum in O(Log n) time, so when we need a data structure with both operations supported efficiently, we use self balancing BSTs.
Advantages:
- Fast search: Searching for a specific value in a BST has an average time complexity of O(log n), where n is the number of nodes in the tree. This is much faster than searching for an element in an array or linked list, which have a time complexity of O(n) in the worst case.
- In-order traversal: BSTs can be traversed in-order, which visits the left subtree, the root, and the right subtree. This can be used to sort a dataset.
Disadvantages:
- Skewed trees: If a tree becomes skewed, the time complexity of search, insertion, and deletion operations will be O(n) instead of O(log n), which can make the tree inefficient.
- Additional time required: Self-balancing trees require additional time to maintain balance during insertion and deletion operations.
- Efficiency: For only search, insert and / or delete operations only hashing is always preferred over BSts. However if we need to maintain sorted data along with these operations, we use BST.
FAQ’s (Frequently asked questions) on Binary Search Tree:
1. What is a Binary Search Tree?
A binary search tree (BST) is a binary tree where every node in the left subtree is less than the root, and every node in the right subtree is of a value greater than the root. The properties of a binary search tree are recursive: if we consider any node as a âroot,â these properties will remain true.
2. What is the Binary Search Tree Operation?
There are major three operations in Binary Search Tree: 1. Insertion, 2. Deletion, 3. Searching. Because of its properties its efficient to search any element in Binary Search Tree.
3. What is Binary Search Tree and AVL tree?
Binary Search Tree: A binary search tree (BST) is a binary tree where every node in the left subtree is less than the root, and every node in the right subtree is of a value greater than the root.
AVL Tree: Binary search trees (BSTs) that self-balance and rotate automatically are known as AVL trees.
4. What are the uses of Binary Search Tree?
Binary search trees can be used to implement sorted stream of data and doubly ended priority queues.
5. What is the difference between binary search tree and binary tree ?
A Binary search tree is a tree that follows some order to arrange the elements, whereas the binary tree does not follow any order.
Related Articles:
Please Login to comment...