简体   繁体   中英

C++ iterative insert into binary search tree BST

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;
  }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM