#include<conio.h>
#include<string.h>
#include<alloc.h>
#include<dos.h>
enum bool{true,false};
typedef struct TreeNode* link;
struct TreeNode {
int item; // The data in this node.
link left; // Pointer to left subtree.
link right; // Pointer to right subtree.
};
struct BinaryTree{
link root;
};
void initTree(link &troot)
{
troot=NULL;
}
void treeInsert(link &troot,int newItem) {
if(troot==NULL){
link temp;
temp=(TreeNode*)malloc(sizeof(TreeNode));
temp->item=newItem;
temp->left=NULL;
temp->right=NULL;
troot=temp;
return;
}
else if ( newItem <troot->item ) {
treeInsert( troot->left, newItem );
}
else {
treeInsert( troot->right, newItem );
}
}
void preordertraverse( link troot ) {
if ( troot != NULL ) {
cout << troot->item << " "; // Print the root item.
preordertraverse( troot->left ); // Print items in left subtree.
preordertraverse( troot->right ); // Print items in right subtree.
}
}
void postordertraverse( link troot ) {
if ( troot != NULL ) {
postordertraverse( troot->left ); // Print items in left subtree.
postordertraverse( troot->right ); // Print items in right subtree.
cout << troot->item << " "; // Print the root item.
}
}
void inordertraverse( link troot ) {
if ( troot != NULL ) {
inordertraverse( troot->left ); // Print items in left subtree.
cout << troot->item << " "; // Print the root item.
inordertraverse( troot->right ); // Print items in right subtree.
}
}
bool treeContains( link troot, int item ) {
if ( troot == NULL ) {
// Tree is empty, so it certainly doesn't contain item.
return false;
}
else if ( item == troot->item ) {
// Yes, the item has been found in the root node.
return true;
}
else if ( item < troot->item ) {
// If the item occurs, it must be in the left subtree.
return treeContains( troot->left, item );
}
else {
// If the item occurs, it must be in the right subtree.
return treeContains( troot->right, item );
}
}
void main(){
clrscr();
BinaryTree *bt;
initTree(bt->root);
treeInsert(bt->root,100);
treeInsert(bt->root,90);
treeInsert(bt->root,120);
treeInsert(bt->root,70);
treeInsert(bt->root,95);
treeInsert(bt->root,130);
cout<<"inserted items : 100 90 120 70 95 130\n\n";
cout<<"Inorder traverse : \n\n";
inordertraverse(bt->root);
cout<<"\n\n";
cout<<"post order traverse : \n\n";
postordertraverse(bt->root);
cout<<endl<<endl;
cout<<"preorder traverse :\n\n";
preordertraverse(bt->root);
cout<<endl;
getch();
}
No comments:
Post a Comment