You are on page 1of 4

#include <iostream>

#include <conio.h>
using namespace std;

struct TreeNode
{
char data;
TreeNode* LC;
TreeNode* RC;

};

class BinaryTree
{
private:
TreeNode* root;
public:
BinaryTree()
{
root = NULL;
}

BinaryTree(TreeNode* x)
{
root = x;
}

BinaryTree* MakeLeftRoot()
{
return (new BinaryTree(root->LC));

BinaryTree* MakeRightRoot()
{
return (new BinaryTree(root->RC));

void AddRootData(char temp)


{
if(root != NULL)
cout<<"\nSorry Root already Exits";
else
{
root = new TreeNode;
root->data = temp;
root->LC = NULL;
root->RC = NULL;

}
}

void AddLeftChild(char temp)


{
if(root == NULL)
cout<<"\nSorry Root already Empty";
else
{
TreeNode* t = new TreeNode;
t->data = temp;
root->LC = t;
t->LC = NULL;
t->RC = NULL;

}
}

void AddRightChild(char temp)


{
if(root == NULL)
cout<<"\nSorry Root already Empty";
else
{
TreeNode* t = new TreeNode;
t->data = temp;
root->RC = t;
t->LC = NULL;
t->RC = NULL;

}
}

void Inorder()
{
if(root==NULL) cout<<"\nNothing to Print, Empty Tree";
Inorder(root);
}

void Preorder()
{
if(root==NULL) cout<<"\nNothing to Print, Empty Tree";
Preorder(root);
}
void Postorder()
{
if(root==NULL) cout<<"\nNothing to Print, Empty Tree";
Postorder(root);
}
void InsertBST(char data)
{
InsertBST(data, root);
}
private:

void InsertBST(char data, TreeNode* r)


{
BinaryTree* bt;
if(r==NULL)
AddRootData(data);
else
{
if(r->data < data)
if(r->RC == NULL)
AddRightChild(data);
else{
bt = MakeRightRoot();
bt->InsertBST(data, bt->root);
}
else
if(r->LC == NULL)
AddLeftChild(data);
else{
bt = MakeLeftRoot();
bt->InsertBST(data, bt->root);
}
}
}
void Inorder(TreeNode* r)
{
if(r != NULL)
{
Inorder(r->LC);
cout<<" "<<r->data;
Inorder(r->RC);
}
}

void Postorder(TreeNode* r)
{
if(r != NULL)
{

Postorder(r->LC);
Postorder(r->RC);
cout<<" "<<r->data;
}
}

void Preorder(TreeNode* r)
{
if(r != NULL)
{

cout<<" "<<r->data;
Preorder(r->LC);
Preorder(r->RC);

}
}

};

int main()
{
BinaryTree *myTree = new BinaryTree();

myTree->InsertBST('U');
myTree->InsertBST('A');
myTree->InsertBST('B');
myTree->InsertBST('J');
myTree->InsertBST('K');
myTree->InsertBST('Z');
myTree->InsertBST('M');
myTree->InsertBST('T');
myTree->InsertBST('C');
cout<<"\nInorder Traversal ";
myTree->Inorder(); //InOrder Traversalof a BST gives Sorted Output

cout<<"\nPreOrder Traversal ";


myTree->Preorder();

cout<<"\nPostOrder Traversal ";


myTree->Postorder();

getch();
}

You might also like