- #1
Eruditee
- 13
- 0
Homework Statement
Binary Tree/ Insertion scheme
Homework Equations
N/A
The Attempt at a Solution
Code:
bool treeNodeADT::_insert(int item) {
if(this->isRootted==false){
this->root=new node;
this->root->data=item;
this->root->right=0;
this->root->left=0;
this->isRootted = true;
}
else if (item>this->root->data){
nodep temp = this->root->right;
while (temp!=0){
if(temp->data>item)
temp=temp->left;
else if (temp->data<item)
temp = temp->right;
else return false;
}
temp = new node;
temp->data=item;
temp->left=0;
temp->right=0;
}
else if (item<this->root->data){
nodep temp = this->root->left;
while (temp!=0){
if(temp->data>item)
temp=temp->left;
else if (temp->data<item)
temp = temp->right;
else return false;
}
temp = new node;
temp->data=item;
temp->left=0;
temp->right=0;
}
}
In short, there's a static variable in which isRotted (mispelled) shows whether the root has been constructed. I then follows the root in either its left or right directions by the if/esls shceme. Then when it gets to a point in which the data shows contrast, it decides to move left or right until a blank node has been found.
I never get into the whiles. Help? I can do this iteratively, but after I found out that's more computationally expensive, I want to learn this way in the event I need to use it for time sensitive cases.