BST iterative insert for binary search tree

Hello!

I'm writing the function as described in the title but it isn't quite working. It works as long as the value passed is less than the parent (going left) but when the value should be placed to the right, it doesn't actually insert the node.

Could someone please tell me why?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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;
  }
}


FYI, I've commented out setting the children of the new leaf to NULL because the constructor already does that.
34
35
36
37
if (child->data < parent->data)
	  parent->left = child;
	else if (child->data < parent->data)
	  parent->right = child;
Topic archived. No new replies allowed.