pertemuan ke 5, Binary Search Tree, 2101678775, Rafael Kevin Liman
Binary Search Tree
Binary Search Tree Operations
•
Binary Search Tree has the following basic operations:
– find(x) : find key x in the BST
– insert(x) : insert new key x into BST
– remove(x) : remove key x from BST
Operations: Search
Because
all data in 2-3 tree are stored in sorted order, searching in 2-3 tree is easy.
We can extend the search algorithm for binary search tree to obtain the search
algorithm in 2-3 tree.
find(ptr, x)
If ptr is NULL then not found
If x = A then found
If x < A then find(ptr->left, x)
If ptr is 3-node
If x = B then found
If A < x and x < B then find(ptr->middle, x)
If B < x then find(ptr->right,x)
Operations: Insertion
Insert operation is to insert one
or more data elements into an array. Based on the requirement, new element can
be added at the beginning, end or any given index of array.
Here, we see a practical
implementation of insertion operation, where we add data at the end of the
array.
Algorithm:
Step 1: IF TREE
= NULL, then
Allocate
memory for TREE
SET TREE->DATA = VAL
SET TREE->LEFT = TREE
->RIGHT = NULL
ELSE
IF VAL < TREE->DATA
Insert(TREE->LEFT,
VAL)
ELSE
Insert(TREE->RIGHT,
VAL)
[END OF IF]
[END OF IF]
Step 2: End
or
Example
#include <stdio.h>
void main()
{
int LA[] = {2,4,6,8,9};
int item = 11, k = 3, n = 5;
int i = 0, j = n;
printf("The original array elements
are:\n");
for(i = 0; i<n; i++)
{
printf("LA[%d] = %d
\n", i, LA[i]);
}
n = n + 1;
while( j >= k)
{
LA[j+1] = LA[j];
j = j - 1;
}
LA[k] = item;
printf("The array elements after
insertion:\n");
for(i = 0; i<n; i++)
{
printf("LA[%d] = %d
\n", i, LA[i]);
}
}
Operations: Deletion
Example
Consider LA is a linear array with N elements and K is a positive
integer such that K<=N.
#include <stdio.h>
void main()
{
int LA[] = {2,4,6,8,9};
int k = 3, n = 5;
int i, j;
printf("The original
array elements are:n");
for(i = 0; i<n; i++)
{
printf("LA[%d]
= %d n", i, LA[i]);
}
j = k;
while( j < n)
{
LA[j-1]
= LA[j];
j = j + 1;
}
n = n -1;
printf("The array
elements after deletion:n");
for(i = 0; i<n; i++)
{
printf("LA[%d]
= %d n", i, LA[i]);
}
}
Komentar
Posting Komentar