0% found this document useful (0 votes)
97 views15 pages

Implementation of BINARY TREE

The document describes the implementation of binary trees in C++. It includes functions to insert nodes, perform preorder, inorder and postorder tree traversals, and a main function to test the tree operations. Node insertion alternates left and right, and the traversals recursively print node data by traversing left and right subtrees.

Uploaded by

rupeshk_p
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
97 views15 pages

Implementation of BINARY TREE

The document describes the implementation of binary trees in C++. It includes functions to insert nodes, perform preorder, inorder and postorder tree traversals, and a main function to test the tree operations. Node insertion alternates left and right, and the traversals recursively print node data by traversing left and right subtrees.

Uploaded by

rupeshk_p
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 15

http://users.cs.fiu.edu/~weiss/dsaa_c2e/files.

html
#include "tree.h"
#include <stdlib.h>
#include "fatal.h"

struct TreeNode
{
ElementType Element;
SearchTree Left;
SearchTree Right;
};

/* START: fig4_17.txt */
SearchTree
MakeEmpty( SearchTree T )
{
if( T != NULL )
{
MakeEmpty( T->Left );
MakeEmpty( T->Right );
free( T );
}
return NULL;
}
/* END */

/* START: fig4_18.txt */
Position
Find( ElementType X, SearchTree T )
{
if( T == NULL )
return NULL;
if( X < T->Element )
return Find( X, T->Left );
else
if( X > T->Element )
return Find( X, T->Right );
else
return T;
}
/* END */

/* START: fig4_19.txt */
Position
FindMin( SearchTree T )
{
if( T == NULL )
return NULL;
else
if( T->Left == NULL )
return T;
else
return FindMin( T->Left );
}
/* END */

/* START: fig4_20.txt */
Position

Implementation of BINARY TREE 1


FindMax( SearchTree T )
{
if( T != NULL )
while( T->Right != NULL )
T = T->Right;

return T;
}
/* END */

/* START: fig4_22.txt */
SearchTree
Insert( ElementType X, SearchTree T )
{
/* 1*/ if( T == NULL )
{
/* Create and return a one-node tree */
/* 2*/ T = malloc( sizeof( struct TreeNode ) );
/* 3*/ if( T == NULL )
/* 4*/ FatalError( "Out of space!!!" );
else
{
/* 5*/ T->Element = X;
/* 6*/ T->Left = T->Right = NULL;
}
}
else
/* 7*/ if( X < T->Element )
/* 8*/ T->Left = Insert( X, T->Left );
else
/* 9*/ if( X > T->Element )
/*10*/ T->Right = Insert( X, T->Right );
/* Else X is in the tree already; we'll do nothing */

/*11*/ return T; /* Do not forget this line!! */


}
/* END */

/* START: fig4_25.txt */
SearchTree
Delete( ElementType X, SearchTree T )
{
Position TmpCell;

if( T == NULL )
Error( "Element not found" );
else
if( X < T->Element ) /* Go left */
T->Left = Delete( X, T->Left );
else
if( X > T->Element ) /* Go right */
T->Right = Delete( X, T->Right );
else /* Found element to be deleted */
if( T->Left && T->Right ) /* Two children */
{
/* Replace with smallest in right subtree */
TmpCell = FindMin( T->Right );
T->Element = TmpCell->Element;

Implementation of BINARY TREE 2


T->Right = Delete( T->Element, T->Right );
}
else /* One or zero children */
{
TmpCell = T;
if( T->Left == NULL ) /* Also handles 0 children */
T = T->Right;
else if( T->Right == NULL )
T = T->Left;
free( TmpCell );
}

return T;
}
/* END */

ElementType
Retrieve( Position P )
{
return P->Element;
}

Implementation of BINARY TREE 3


Implementation of BINARY TREE
Shows the implementation using C++
1. #include<iostream.h>
2.           #include<conio.h>
3.           #include<stdio.h>
4.           #include<stdlib.h>
5.           struct node
6.           {
7.                int data;
8.                node *left;
9.                node *right;
10.           };
11.  
12.           node *tree=NULL;
13.           node *insert(node *tree,int ele);
14.  
15.           void preorder(node *tree);
16.           void inorder(node *tree);
17.           void postorder(node *tree);
18.           int count=1;
19.  
20.           void main()
21.           {
22.                clrscr();
23.                int ch,ele;
24.                do
25.                {
26.                     clrscr();
27.                     cout<<"\n\t\a\a1----INSERT A NODE IN A BINARY TREE.\a\a";
28.                     cout<<"\n\t\a\a2----PRE-ORDER TRAVERSAL.\a\a";
29.                     cout<<"\n\t\a\a3----IN-ORDER TRAVERSAL.\a\a";
30.                     cout<<"\n\t\a\a4----POST-ORDER TRAVERSAL.\a\a";
31.                     cout<<"\n\t\a\a5----EXIT.\a\a";
32.                     cout<<"\n\t\a\aENTER CHOICE::\a\a";
33.                     cin>>ch;
34.                     switch(ch)
35.                {
36.                          case 1:
37.                          cout<<"\n\t\a\aENTER THE ELEMENT::\a\a";
38.                          cin>>ele;
39.                          tree=insert(tree,ele);
40.                          break;
41.  
42.                          case 2:
43.                          cout<<"\n\t\a\a****PRE-ORDER TRAVERSAL OF A TREE****\a\a";
44.                          preorder(tree);
45.                          break;
46.  
47.                          case 3:
48.                          cout<<"\n\t\a\a****IN-ORDER TRAVERSAL OF A TREE****\a\a";
49.                          inorder(tree);
50.                          break;
51.  
52.                          case 4:
53.                          cout<<"\n\t\a\a****POST-ORDER TRAVERSAL OF A TREE****\a\a";
54.                          postorder(tree);
55.                          break;

Implementation of BINARY TREE 4


56.  
57.                         case 5:
58.                         exit(0);
59.                 }
60.               }while(ch!=5);
61.           }
62.  
63.           node *insert(node *tree,int ele)
64.           {
65.                if(tree==NULL)
66.                {
67.                     tree=new node;
68.                     tree->left=tree->right=NULL;
69.                     tree->data=ele;
70.                     count++;
71.                }
72.                else
73.                if(count%2==0)
74.                tree->left=insert(tree->left,ele);
75.                else
76.                tree->right=insert(tree->right,ele);
77.                return(tree);
78.           }
79.  
80.           void preorder(node *tree)
81.           {
82.                if(tree!=NULL)
83.                {
84.                     cout<<tree->data;
85.                     preorder(tree->left);
86.                     preorder(tree->right);
87.                     getch();
88.                }
89.           }
90.  
91.           void inorder(node *tree)
92.           {
93.                if(tree!=NULL)
94.                {
95.                     inorder(tree->left);
96.                     cout<<tree->data;
97.                     inorder(tree->right);
98.                     getch();
99.                }
100.           }
101.  
102.           void postorder(node *tree)
103.           {
104.                if(tree!=NULL)
105.                {
106.                     postorder(tree->left);
107.                     postorder(tree->right);
108.                     cout<<tree->data;
109.                     getch();
110.                }
111.           }

Implementation of BINARY TREE 5


/* This file contains a collection of sorting routines */

#include <stdlib.h>
#include "fatal.h"

typedef int ElementType;

void
Swap( ElementType *Lhs, ElementType *Rhs )
{
ElementType Tmp = *Lhs;
*Lhs = *Rhs;
*Rhs = Tmp;
}

/* START: fig7_2.txt */
void
InsertionSort( ElementType A[ ], int N )
{
int j, P;
ElementType Tmp;

/* 1*/ for( P = 1; P < N; P++ )


{
/* 2*/ Tmp = A[ P ];
/* 3*/ for( j = P; j > 0 && A[ j - 1 ] > Tmp; j-- )
/* 4*/ A[ j ] = A[ j - 1 ];
/* 5*/ A[ j ] = Tmp;
}
}
/* END */

/* START: fig7_4.txt */
void
Shellsort( ElementType A[ ], int N )
{
int i, j, Increment;
ElementType Tmp;

/* 1*/ for( Increment = N / 2; Increment > 0; Increment /= 2 )


/* 2*/ for( i = Increment; i < N; i++ )
{
/* 3*/ Tmp = A[ i ];
/* 4*/ for( j = i; j >= Increment; j -= Increment )
/* 5*/ if( Tmp < A[ j - Increment ] )
/* 6*/ A[ j ] = A[ j - Increment ];
else
/* 7*/ break;
/* 8*/ A[ j ] = Tmp;
}
}
/* END */

/* START: fig7_8.txt */

#define LeftChild( i ) ( 2 * ( i ) + 1 )

void

Implementation of BINARY TREE 6


PercDown( ElementType A[ ], int i, int N )
{
int Child;
ElementType Tmp;

/* 1*/ for( Tmp = A[ i ]; LeftChild( i ) < N; i = Child )


{
/* 2*/ Child = LeftChild( i );
/* 3*/ if( Child != N - 1 && A[ Child + 1 ] > A[ Child ] )
/* 4*/ Child++;
/* 5*/ if( Tmp < A[ Child ] )
/* 6*/ A[ i ] = A[ Child ];
else
/* 7*/ break;
}
/* 8*/ A[ i ] =Tmp;
}

void
Heapsort( ElementType A[ ], int N )
{
int i;

/* 1*/ for( i = N / 2; i >= 0; i-- ) /* BuildHeap */


/* 2*/ PercDown( A, i, N );
/* 3*/ for( i = N - 1; i > 0; i-- )
{
/* 4*/ Swap( &A[ 0 ], &A[ i ] ); /* DeleteMax */
/* 5*/ PercDown( A, 0, i );
}
}
/* END */

/* START: fig7_10.txt */
/* Lpos = start of left half, Rpos = start of right half */

void
Merge( ElementType A[ ], ElementType TmpArray[ ],
int Lpos, int Rpos, int RightEnd )
{
int i, LeftEnd, NumElements, TmpPos;

LeftEnd = Rpos - 1;
TmpPos = Lpos;
NumElements = RightEnd - Lpos + 1;

/* main loop */
while( Lpos <= LeftEnd && Rpos <= RightEnd )
if( A[ Lpos ] <= A[ Rpos ] )
TmpArray[ TmpPos++ ] = A[ Lpos++ ];
else
TmpArray[ TmpPos++ ] = A[ Rpos++ ];

while( Lpos <= LeftEnd ) /* Copy rest of first half */


TmpArray[ TmpPos++ ] = A[ Lpos++ ];
while( Rpos <= RightEnd ) /* Copy rest of second half */
TmpArray[ TmpPos++ ] = A[ Rpos++ ];

Implementation of BINARY TREE 7


/* Copy TmpArray back */
for( i = 0; i < NumElements; i++, RightEnd-- )
A[ RightEnd ] = TmpArray[ RightEnd ];
}
/* END */

/* START: fig7_9.txt */
void
MSort( ElementType A[ ], ElementType TmpArray[ ],
int Left, int Right )
{
int Center;

if( Left < Right )


{
Center = ( Left + Right ) / 2;
MSort( A, TmpArray, Left, Center );
MSort( A, TmpArray, Center + 1, Right );
Merge( A, TmpArray, Left, Center + 1, Right );
}
}

void
Mergesort( ElementType A[ ], int N )
{
ElementType *TmpArray;

TmpArray = malloc( N * sizeof( ElementType ) );


if( TmpArray != NULL )
{
MSort( A, TmpArray, 0, N - 1 );
free( TmpArray );
}
else
FatalError( "No space for tmp array!!!" );
}
/* END */

/* START: fig7_13.txt */
/* Return median of Left, Center, and Right */
/* Order these and hide the pivot */

ElementType
Median3( ElementType A[ ], int Left, int Right )
{
int Center = ( Left + Right ) / 2;

if( A[ Left ] > A[ Center ] )


Swap( &A[ Left ], &A[ Center ] );
if( A[ Left ] > A[ Right ] )
Swap( &A[ Left ], &A[ Right ] );
if( A[ Center ] > A[ Right ] )
Swap( &A[ Center ], &A[ Right ] );

/* Invariant: A[ Left ] <= A[ Center ] <= A[ Right ] */

Swap( &A[ Center ], &A[ Right - 1 ] ); /* Hide pivot */


return A[ Right - 1 ]; /* Return pivot */

Implementation of BINARY TREE 8


}
/* END */

/* START: fig7_14.txt */
#define Cutoff ( 3 )

void
Qsort( ElementType A[ ], int Left, int Right )
{
int i, j;
ElementType Pivot;

/* 1*/ if( Left + Cutoff <= Right )


{
/* 2*/ Pivot = Median3( A, Left, Right );
/* 3*/ i = Left; j = Right - 1;
/* 4*/ for( ; ; )
{
/* 5*/ while( A[ ++i ] < Pivot ){ }
/* 6*/ while( A[ --j ] > Pivot ){ }
/* 7*/ if( i < j )
/* 8*/ Swap( &A[ i ], &A[ j ] );
else
/* 9*/ break;
}
/*10*/ Swap( &A[ i ], &A[ Right - 1 ] ); /* Restore pivot */

/*11*/ Qsort( A, Left, i - 1 );


/*12*/ Qsort( A, i + 1, Right );
}
else /* Do an insertion sort on the subarray */
/*13*/ InsertionSort( A + Left, Right - Left + 1 );
}
/* END */

/* This code doesn't work; it's Figure 7.15. */


#if 0
/* START: fig7_15.txt */
/* 3*/ i = Left + 1; j = Right - 2;
/* 4*/ for( ; ; )
{
/* 5*/ while( A[ i ] < Pivot ) i++;
/* 6*/ while( A[ j ] > Pivot ) j--;
/* 7*/ if( i < j )
/* 8*/ Swap( &A[ i ], &A[ j ] );
else
/* 9*/ break;
}
/* END */
#endif

/* START: fig7_12.txt */
void
Quicksort( ElementType A[ ], int N )
{
Qsort( A, 0, N - 1 );
}
/* END */

Implementation of BINARY TREE 9


/* START: fig7_16.txt */
/* Places the kth smallest element in the kth position */
/* Because arrays start at 0, this will be index k-1 */
void
Qselect( ElementType A[ ], int k, int Left, int Right )
{
int i, j;
ElementType Pivot;

/* 1*/ if( Left + Cutoff <= Right )


{
/* 2*/ Pivot = Median3( A, Left, Right );
/* 3*/ i = Left; j = Right - 1;
/* 4*/ for( ; ; )
{
/* 5*/ while( A[ ++i ] < Pivot ){ }
/* 6*/ while( A[ --j ] > Pivot ){ }
/* 7*/ if( i < j )
/* 8*/ Swap( &A[ i ], &A[ j ] );
else
/* 9*/ break;
}
/*10*/ Swap( &A[ i ], &A[ Right - 1 ] ); /* Restore pivot */

/*11*/ if( k <= i )


/*12*/ Qselect( A, k, Left, i - 1 );
/*13*/ else if( k > i + 1 )
/*14*/ Qselect( A, k, i + 1, Right );
}
else /* Do an insertion sort on the subarray */
/*15*/ InsertionSort( A + Left, Right - Left + 1 );
}
/* END */

/* ROUTINES TO TEST THE SORTS */

void
Permute( ElementType A[ ], int N )
{
int i;

for( i = 0; i < N; i++ )


A[ i ] = i;
for( i = 1; i < N; i++ )
Swap( &A[ i ], &A[ rand( ) % ( i + 1 ) ] );
}

void
Checksort( ElementType A[ ], int N )
{
int i;
for( i = 0; i < N; i++ )
if( A[ i ] != i )
printf( "Sort fails: %d %d\n", i, A[ i ] );
printf( "Check completed\n" );
}

Implementation of BINARY TREE 10


void
Copy( ElementType Lhs[ ], const ElementType Rhs[ ], int N )
{
int i;
for( i = 0; i < N; i++ )
Lhs[ i ] = Rhs[ i ];
}

#define MaxSize 7000


int Arr1[ MaxSize ];
int Arr2[ MaxSize ];

main( )
{
int i;

for( i = 0; i < 10; i++ )


{
Permute( Arr2, MaxSize );
Copy( Arr1, Arr2, MaxSize );
InsertionSort( Arr1, MaxSize );
Checksort( Arr1, MaxSize );

Copy( Arr1, Arr2, MaxSize );


Shellsort( Arr1, MaxSize );
Checksort( Arr1, MaxSize );

Copy( Arr1, Arr2, MaxSize );


Heapsort( Arr1, MaxSize );
Checksort( Arr1, MaxSize );

Copy( Arr1, Arr2, MaxSize );


Mergesort( Arr1, MaxSize );
Checksort( Arr1, MaxSize );

Copy( Arr1, Arr2, MaxSize );


Quicksort( Arr1, MaxSize );
Checksort( Arr1, MaxSize );

Copy( Arr1, Arr2, MaxSize );


Qselect( Arr1, MaxSize / 2 + 1 + i, 0, MaxSize - 1 );
if( Arr1[ MaxSize / 2 + i ] != MaxSize / 2 + i )
printf( "Select error: %d %d\n", MaxSize / 2 + i ,
Arr1[ MaxSize / 2 + i ] );
else
printf( "Select works\n" );
}

return 0;
}

Implementation of BINARY TREE 11


#include
#include
#define PREORDER 1
#define POSTORDER 2
#define INORDER 3
class TreeNode
{
public:
TreeNode *LChild;
char val;
TreeNode *RChild;
TreeNode()
{
LChild=NULL;
RChild=NULL;
}
};
class Tree
{
private:
TreeNode *Root;
void Attach(TreeNode *t, TreeNode *n)
{
if(t->val>n->val)
{
if(t->LChild==NULL)
t->LChild=n;
else
Attach(t->LChild,n);
}
if(t->valval)
{
if(t->RChild==NULL)
t->RChild=n;
else
Attach(t->RChild,n);
}
}
void PreOrder(TreeNode *t)
{
if(t!=NULL)
{
cout<<" "<val;
PreOrder(t->LChild);
PreOrder(t->RChild);
}
}
void InOrder(TreeNode *t)
{
if(t!=NULL)
{
InOrder(t->LChild);
cout<<" "<val;
InOrder(t->RChild);
}
}
void PostOrder(TreeNode *t)
Implementation of BINARY TREE 12
{
if(t!=NULL)
{
PostOrder(t->LChild);
PostOrder(t->RChild);
cout<<" "<val;
}
}
int search(TreeNode *LocalRoot, int v, TreeNode **x, TreeNode **parent, int *found)
{
*found=0;
*parent=NULL;
*x=NULL;
while((LocalRoot!=NULL)&&(!(*found)))
{
if(LocalRoot->val==v)
{
*found=1;
*x=LocalRoot;
}
else
{
*parent=LocalRoot;
if(LocalRoot->val>v)
LocalRoot=LocalRoot->LChild;
else
LocalRoot=LocalRoot->RChild ;
}
}
}
public:
Tree()
{
Root=NULL;
}
void AddNode(char v)
{
TreeNode *n=new TreeNode;
n->val=v;
if(Root==NULL)
Root=n;
else
Attach(Root,n);
}
void Traverse(int Order)
{
switch(Order)
{
case PREORDER: PreOrder(Root);break;
case POSTORDER: PostOrder(Root);break;
case INORDER: InOrder(Root);
}
cout<LChild!=NULL)&&(x->RChild!=NULL))
{
xsucc=x->RChild;
xc=NULL;
while(xsucc->LChild!=NULL)
{

Implementation of BINARY TREE 13


xc=xsucc;
xsucc=xsucc->LChild;
}
x->val=xsucc->val;
if(xc!=NULL)
xc->LChild=xsucc->RChild;
else
x->RChild=xsucc->RChild;
delete(xsucc);
}
else
{
if(x->LChild!=NULL)
{
if(parent!=NULL)
{
if(parent->LChild==x)
parent->LChild=x->LChild;
else
parent->RChild=x->LChild;
}
else
Root=x->LChild;
}
else
{
if(x->RChild!=NULL)
{
if(parent!=NULL)
{
if(parent->LChild==x)
parent->LChild=x->RChild;
else
parent->RChild=x->RChild;
}
else
Root=x->RChild;
}
else
{
if(parent!=NULL)
{
if(parent->LChild==x)
parent->LChild=NULL;
else
parent->RChild=NULL;
}
else
Root=NULL;
}
}
delete(x);
}
}
}
}
};
void main()

Implementation of BINARY TREE 14


{
Tree s;
char ch,x;
do
{
clrscr();
cout<<"Tree"<<<"Pre Order: ";
s.Traverse(PREORDER);
cout<<"In Order: ";
s.Traverse(INORDER);
cout<<"Post Order: ";
s.Traverse(POSTORDER);
cout<<"Menu..."<<<"1. Insert"<<endl<<"2. Remove"<<<"3. Exit"<<endl<<"Enter the Choice: ";
ch=getche();
switch(ch-48)
{
case 1:
cout<<endl<<"Enter the Charactor to be Inserted: ";
x=getche();
getch();
s.AddNode(x);
break;
case 2:
cout<<endl<<"Enter the Charactor to be Removed: ";
x=getche();
s.Remove(x);
getch();
break;
}
}while(ch-48!=3);
}

Implementation of BINARY TREE 15

You might also like