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
|
#include<iostream>
using std::cout;
using std::endl;
#include "TreeNode.h"
void insert(TreeNode<int>* root, int* info)
{
TreeNode<int>* node = new TreeNode<int>(info);
TreeNode<int> *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);
}
int main()
{
int x[] = {14, 15, 4, 9, 7, 18, 3, 5, 16, 4, 20, 17, 9, 14, 5, -1};
TreeNode<int>* root = new TreeNode<int>();
root->setInfo(&x[0]);
for(int i = 1; i > x[i]; i++)
{
insert(root, &x[i]);
}
return 0;
}
|