Binary search tree
This Code Show Me the garbage value when I call the display function..Whts the prblm??
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
|
#include<iostream>
using namespace std;
class Node{
int data;
Node *left;
Node *right;
public:
Node *root;
Node(){
root=NULL;
}
void inOrderDisplay(Node *root){
if(root!=NULL)
{
inOrderDisplay(root->left);
cout<<root->data<<endl;
inOrderDisplay(root->right);
}
}
void process(Node *newParent, Node *oldParent){
if(oldParent==NULL){
return;
}
else if(oldParent->data>newParent->data){
if(oldParent->left=NULL){
oldParent->left=newParent;
}
process(newParent,oldParent->left);
}
else{
if(oldParent->right=NULL){
oldParent->right=newParent;
}
process(newParent,oldParent->right);
}
}
void insertNode(){
if(root==NULL){
root=new Node;
cout<<"Enter Value ";
cin>>data;
root->left=NULL;
root->right=NULL;
}
else{
Node *parent;
parent=new Node;
cout<<"Enter value ";
cin>>data;
parent->left=NULL;
parent->right=NULL;
process(parent,root);
}
}
};
int main(){
Node p;
int ch;
do{
cout<<"Enter 1 To Insert "<<endl;
cout<<"Enter 2 To display "<<endl;
cin>>ch;
if(ch==1){p.insertNode();}
if(ch==2){p.inOrderDisplay(p.root);}
}
while(ch!=3);
}
| |
Logically, there is no reason for a Node to know what a root is and you seem to be conflating the notion of a root and a parent.
If I were you, I'd get rid of line 12.
your problem is in insertnode function:
you may replace it with this and also delete process function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
|
#include<iostream>
using namespace std;
class Node{
int data;
Node *left;
Node *right;
public:
Node *root;
Node():left(NULL),right(NULL),root(NULL){}
void inOrderDisplay(Node *root){
if(root!=NULL)
{
inOrderDisplay(root->left);
cout<<root->data<<endl;
inOrderDisplay(root->right);
}
}
void insert()
{
int item;
cout<<"Enter data : ";cin>>item;
Node* parent=NULL;
Node* locptr=root;
bool found=false;
while(!found&&locptr!=NULL)
{
parent=locptr;
if(item<locptr->data)
locptr=locptr->left;
else if(item>locptr->data)
locptr=locptr->right;
else
found=true;
}
if(!found)
{
locptr=new Node;
locptr->data=item;
if(parent==NULL)
root=locptr;
else if(item<parent->data)
parent->left=locptr;
else
parent->right=locptr;
}else
cout<<"Item already in the tree\a\n";
}
};
int main(){
Node p;
int ch;
do{
cout<<"Enter 1 To Insert "<<endl;
cout<<"Enter 2 To display "<<endl;
cin>>ch;
if(ch==1){p.insert();}
if(ch==2){p.inOrderDisplay(p.root);}
}
while(ch!=3);
}
| |
Topic archived. No new replies allowed.