As it can be seen from my class, I am quite having a hard time figuring out how the insert function should. My problem is how I keep updating the pointers to the right position.
I kinda have an idea how i should make the insert function , but updating the pointers seems a bit complex..
void tree::insert(int i){
node* temp = root;
if (i < root->value) {
while (/*check value of leftvalue pointer != null*/) {
//update leftvalue pointer with next
if (i > /*leftvalue*/) {
//create a right node.
}
}
}else{
while (/*check value of rightvalue pointer != null*/) {
//update rightvalue pointer with next
if (i> /*rightvalue*/) {
//create a left node.
}
}
if (i > root->value) {
while (/*check value of leftvalue pointer != null*/) {
//update leftvalue pointer with next
if (i> /*leftvalue*/) {
//create a right node.
}
}
}else{
while (/*check value of rightvalue pointer != null*/) {
//update rightvalue pointer with next
if (i> /*rightvalue*/) {
//create a left node.
}
}
}
I would maybe use a recursive insert instead. Something like this (I haven't tested this tho)
1 2 3 4 5 6 7 8 9 10 11 12 13
void node::insert(int i){
if (i < node->value) {
if (left)
left->insert(i);
else
left = new Node(i);
} else (i > node->value) {
if (right)
right->insert(i);
else
right = new Node(i);
}
}
and then when you want to insert an int into the tree, you just insert it in the root-node.