Reputation: 3407
hi I was writing a BST and wrote following function for adding Child.
void addChild(T value)
{
temp = root;
while(0 != temp)
{
temp1 = temp;
if(value > temp->getValue())
temp = temp->getRightChild();
else
temp = temp->getLeftChild();
}
if(temp1->getValue() > value)
{
temp1->setRightChild(new Child(value));
}
else
{
temp1->setLeftChild(new Child(value));
}
}
I am giving "23 12 122 1 121 15" as input. Root is node 23 which i am creating in constructor of class.
Problem: When i am doing tree traversal i am getting only 23 and 15 as output. Question : What am i doing wrong in this function ?
Upvotes: 1
Views: 92
Reputation: 9785
I agree with previous answers by Captain and sje, but they don't explain the severe, should we say, underpopulation of your tree. The possible problem is that you add value as a child of temp1, discarding previous child altogether. That is probably done in T::setRightChild() and T::setLeftChild() functions.
Upvotes: 0
Reputation: 14705
The conditions are mixed up.
if(value > temp->getValue()) : getRight
is the opposite to
if(temp1->getValue() > value) : setRight
Try just changing the last condition.
Upvotes: 1
Reputation: 41802
Try:
if(value > temp1->getValue())
...otherwise your insertion condition differs from your search for a spot in the loop above.
Upvotes: 1