Question

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 ?

Was it helpful?

Solution

Try:

if(value > temp1->getValue()) 

...otherwise your insertion condition differs from your search for a spot in the loop above.

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top