Hi i have weird doubt. My assingment is C++ program to insert and delete elements in Binary Search Tree.I am almost done wid the assingment. But the major part lies here. the strucure of the output is difficult to obtain.. i will explzin the question now.
Input:
F
D
R
P
M
N
V
Output:
F
+-- D
| +-- NULL
| \-- NULL
\-- R
+-- P
| +-- M
| | +-- NULL
| | \-- N
| | +-- NULL
| | \-- NULL
| \-- NULL
\-- V
+-- NULL
\-- NULL
I am done wid the ouput but iam not able to do the Vertical lines "|".. can anyone help me.. wid the logic. I am doing preorder...
CODE for PREORDER arrangement of ELEMENTS....
void BST::inorder(struct Node *p,int b)
{
if(p!=NULL)
{
printf("%s",p->element);
cout<<endl;
if(p->left == NULL)
{
for(int i=4;i<b;i++)
{
cout<<" ";
}
cout<<"+-- NULL"<<endl;
}
else if(p->left!= NULL)
{
for(int i=4;i<b;i++)
{
cout<<" ";
}
cout<<"+-- ";
inorder(p->left,b+5);
}
if(p->right==NULL)
{
for(int i=4;i<b;i++)
{
cout<<" ";
}
cout<<"\\-- NULL"<<endl;
}
else if(p->right!=NULL)
{
for(int i=4;i<b;i++)
{
cout<<" ";
}
cout<<"\\-- ";
inorder(p->right,b+5);
}
}
}
CODE FOR INSERT OPERATION
void BST::insert(char* data)
{
Node* n = new Node;
strcpy(n->element,data);
n->left = NULL;
n->right = NULL;
if(root == NULL)
{
root = n;
cout<<endl;
cout<<"INSERTED: "<<data<<" as ROOT Element"<<endl;
cout<<endl;
n->breadth=0;
inorder(root,n->breadth);
return;
}
Node* tmp = root;
while(tmp)
{
if(strcmp(data,tmp->element)<0)
{
if(tmp->left == NULL)
{
tmp->left = n;
n->breadth=n->breadth+5;
cout<<endl;
cout<<"INSERTED: "<<data<<endl;
cout<<endl;
inorder(root,n->breadth);
return;
}
else
{
tmp = tmp->left;
}
}
else
{
if(tmp->right == NULL)
{
tmp->right = n;
n->breadth=n->breadth+5;
cout<<endl;
cout<<"INSERTED: "<<data<<endl;
cout<<endl;
inorder(root,n->breadth);
return;
}
else
{
tmp = tmp->right;
}
}
}
}
CLASS DECLARATION
class BST
{
public:
struct Node
{
char element[10];
Node* left;
Node* right;
int breadth;
};
Node* root;
BST()
{
root = NULL;
}
~BST()
{
}
void insert(char*);
void remove(char*);
void inorder(struct Node*,int);
void delorder(struct Node*,int);
};