Data Structure Using C++
Tree Data Structure
Binary Search Tree
(Insert Function) Binary Search Tree
#include "treeNode.cpp"
void insert(treeNode* root, int info);
using namespace std;
int main()
{
int x[] = { 14, 15, 4, 9, 7, 18, 3, 5, 16,4, 20, 17, 9, 14, 5, -1};
treeNode *root = new treeNode();
root->setInfo(x[0]);
for(int i=1; x[i]>0; i++ )
{
insert(root, x[i] );
}
}
void insert(treeNode* root, int info)
{
treeNode* node = new treeNode(info);
treeNode *p, *q;
p = q = root;
while(info!=(p->getInfo()) && q!= NULL )
{
p = q;
if( info < p->getInfo() )
q = p->getLeft();
else
q = p->getRight();
}
if( info == p->getInfo() ){
cout << "attempt to insert duplicate: " << info << endl;
delete node;
}
else if( info < p->getInfo() )
p->setLeft( node );
else
p->setRight( node );
} // end of insert
Let me know in the comment section if you have any question.
Previous Post:
Tree Node Template In Data Structure Using C++
Comments
Post a Comment