1

My function works as long as item is smaller and therefore inserted to the left, but when it should go right, nothing seems to happen. It doesn't crash or anything, it just doesn't do the insert.

I don't get how this could happen because the only different in the code in either case is the words left or right (as far as I can see). Anything obvious to someone more experienced?

template <typename T>
void BST<T>::insertHelper(BST<T>::BinNodePtr &subRoot, const T& item)
{
  BinNode *newNode;
  BinNode *parent;
  BinNode *child;

  newNode = new BinNode;
  newNode->data = item;
  // newNode->left = NULL;
  // newNode->right = NULL;

  parent = subRoot;
  child = subRoot;

  if (!subRoot){
    subRoot = newNode;
  } else {

    if (item < child->data){
      child = child->left;
    } else if (item > child->data){
      child = child->right;
    }
    while (child){
      parent = child;
      if (item < child->data){
        child = child->left;
      } else if (item > child->data){
        child = child->right;
      }
    }
    child = newNode;
    if (child->data < parent->data)
      parent->left = child;
    else if (child->data < parent->data)
      parent->right = child;
  }
}
2
  • just put some printf() debug outputs here and there to follow how the decisions at every if are made, and you will see the wrong decision in the last if clause. Commented May 13, 2014 at 22:49
  • if item == subRoot->data the while go in a endless loop. What is T in your test case? T have a comparison operator override? Commented May 13, 2014 at 22:50

1 Answer 1

3

Your last 'if' and 'else if' have the same condition. The second one should be '>'

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.