Reputation: 121
This is the code I am writing for insertion and inorder traversal of a binary tree. However I am kind of messed up now. Could you please help me in correcting this? The while loop in the insert-code is not getting anything getting inside into it. Thanks for your help.
#include<iostream>
#include<string>
using namespace std;
class binarynode
{public:
string data;
binarynode *left;
binarynode *right;
};
class tree
{
binarynode *root;
public:
tree()
{
root=new binarynode;
root=NULL;
}
binarynode* createnode(string value)
{
binarynode * temp;
temp=new binarynode;
temp->data=value;
temp->left=NULL;
temp->right=NULL;
return temp;
}
void insert(string value)
{//cout<<"entered 1"<<endl;
binarynode * nroot;
nroot=root;
while(nroot!=NULL)
{//cout<<"here 2"<<endl;
if(value> nroot->data )
{
// cout<<"here 3"<<endl;
nroot=nroot->right;
}
else
if(value<nroot->data)
{//cout<<"here 4"<<endl;
nroot=nroot->left;
}
}
nroot=createnode(value);
}
void inorder()
{
binarynode *nroot;
nroot=root;
printinorder(nroot);
}
void printinorder(binarynode * nroot)
{
//cout<<"entered 5"<<endl;
if(nroot->left==NULL&&nroot->right==NULL)
{
cout<<nroot->data<<" ";
}
printinorder(nroot->left);
cout<<nroot->data<<" ";
printinorder(nroot->right);
}
};
int main()
{
tree a;
int n;
cin>>n;
for(int i=0;i<n;i++)
{
string value;
cin>>value;
a.insert(value);
}
a.inorder();
}
Upvotes: 0
Views: 107
Reputation: 3970
Note that nroot=createnode(value);
won't append a node to the tree. You can use double pointers for this.
Edit: as requested by yeldar
void insert(const std::string& value) {
binarynode **node = &root;
while (*node) {
if (value >= (*node)->data) {
node=&(*node)->right;
} else {
node=&(*node)->left;
}
}
*node=createnode(value);
}
Edit: not using double pointers
void insert(const std::string& value) {
if (root == NULL) {
root = createnode(value);
return;
}
binarynode *node = root;
binarynode *parent = NULL;
while (node) {
parent = node; // we should store the parent node
node = value >= parent->data ? parent->right : parent->left;
}
if (value >= parent->data) {
parent->right = createnode(value);
} else {
parent->left = createnode(value);
}
}
Upvotes: 1
Reputation: 525
You are assigning NULL to root in the constructor:
root = NULL;
so your while loop will never be entered.
Upvotes: 2