Professional Documents
Culture Documents
Binary Search Trees11111
Binary Search Trees11111
understanding:
C function to search a given key
in a given BST
struct node* search(struct node* root, int key)
#include <stdlib.h>
{
#include <stdio.h> if (root == NULL || root->key == key)
struct node { return root;
int key; if (root->key < key)
struct node *left, *right; return search(root->right, key);
}; return search(root->left, key);
}
struct node* newNode(int item)
int main()
{
{
struct node* temp struct node* root = NULL;
= (struct node*)malloc(sizeof(struct node)); root = insert(root, 50);
temp->key = item; insert(root, 30);
temp->left = temp->right = NULL; insert(root, 20);
return temp; insert(root, 40);
insert(root, 70);
}
insert(root, 60);
struct node* insert(struct node* node, int key)
insert(root, 80);
{ int key = 6;
if (node == NULL) if (search(root, key) == NULL)
return newNode(key); printf("%d not found\n", key);
if (key < node->key) else
node->left = insert(node->left, key); printf("%d found\n", key);
key = 60;
else if (key > node->key)
node->right = insert(node->right, key);
return node;
}
if (search(root, key) == NULL)
printf("%d not found\n", key);
else
printf("%d found\n", key);
return 0;
}
OUTPUT:
6 not found
60 found
Applications of BST
Binary Search Tree (BST) is a data structure that is commonly used to implement
efficient searching, insertion, and deletion operations. The key feature of a BST is
that it is a binary tree, where each node has at most two child nodes, and the value
of each node is greater than all the values in its left subtree and less than all the
values in its right subtree
Due to this property, BSTs allow for efficient searching by repeatedly dividing the
search space in half, which makes it an important data structure and many other
fields.
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.
A Self-Balancing Binary Search Tree is used to
maintain sorted stream of data. For example,
suppose we are getting online orders placed and
we want to maintain the live data (in RAM) in
sorted order of prices. For example, we wish to
know number of items purchased at cost below a
given cost at any moment