i want to implement a binary tree code but i encountered a problem. after i insert some numbers to tree, i couldn't print my numbers except first one or i couldn't insert the numbers except first one. As a result my binary tree doesn't work, it only shows the first(root) value. where is the problem? inserting or printing numbers?
here is my header file
struct node{
int index;
node *rnode;
node *lnode;
};
class MyTree
{
public:
MyTree(void);
void traverseInOrder();
bool isEmpty()const;
bool search(int item);
bool insert(int newItem);
private:
bool searchByNode(int item, node *ptr);
void inOrder(node *ptr);
node *root;
};
//here is implementation
#include "MyTree.h"
#include <iostream>
using namespace std;
MyTree::MyTree(void)
{
root=0;
}
bool MyTree::isEmpty()const{
if(root==0)
return true;
else
return false;
}
void MyTree::traverseInOrder(){
inOrder(root);
}
void MyTree::inOrder(node *ptr){
if(ptr!=0)
{
inOrder(ptr->lnode);
cout<<ptr->index<<endl;
inOrder(ptr->rnode);
}
}
bool MyTree::insert(int newItem){
node *newNode= new node();
newNode->index=newItem;
newNode->lnode=0;
newNode->rnode=0;
node *current, *trailCurrent;
if(isEmpty()){
root=newNode;
return true;
}
else{
current=root;
while(current!=0)
{
trailCurrent=current;
if(current->index==newItem)
cout<<"there is already such item"<<endl;
else{
if( newItem > current->index )
current=current->rnode;
else
current=current->lnode;
}
}
if(trailCurrent->index < newItem)
newNode=trailCurrent->rnode;
else
newNode=trailCurrent->lnode;
return true;
}
return false;
}
bool MyTree::search(int item){
return searchByNode(item,root);
}
bool MyTree::searchByNode(int item, node *ptr){
if(item==ptr->index)
return true;
else{
if(item>ptr->index)
searchByNode(item,ptr->rnode);
else
searchByNode(item,ptr->lnode);
}
return false;
}
//main
MyTree test;
test.insert(9);
test.insert(13);
test.insert(10);
cout<<"traverse inorder:"<<endl;
test.traverseInOrder();
Thank you...