# Binary Search Tree Insert

• 04-29-2010
bleuz
Binary Search Tree Insert
Ok so we are doing Binary Search Trees. I have to do an insert function to add new data into the tree. The code below calls a recursive function to do this. However we are required to do this non recursively.

I have absolutely no idea where to start for this. a little guidance would be greatly appreciated. Thank you :)

Code:

```void Insert(string data) {         if (root != NULL)         {                 Insert(data, root);         }         else         {                 root = new node;                 root->data = data;                 root->left = NULL;                 root->right = NULL;         } }```
• 04-29-2010
IceDane
Quote:

Originally Posted by bleuz
Ok so we are doing Binary Search Trees. I have to do an insert function to add new data into the tree. The code below calls a recursive function to do this. However we are required to do this non recursively.

I have absolutely no idea where to start for this. a little guidance would be greatly appreciated. Thank you :)

Code:

```void Insert(string data) {         if (root != NULL)         {                 Insert(data, root);         }         else         {                 root = new node;                 root->data = data;                 root->left = NULL;                 root->right = NULL;         } }```

You simply loop through the tree, going down left or right as the data you want to insert dictates, until you find a 0-node. Then you create it and insert the data.
• 04-29-2010
iMalc
You do it in the same way you append a node to a linked-list, except that you take one of two possible paths from each node. Can you append to a linked-list?
• 04-29-2010
bleuz
Quote:

Originally Posted by iMalc
You do it in the same way you append a node to a linked-list, except that you take one of two possible paths from each node. Can you append to a linked-list?

Yes I can. so all im doing is checking whether my data to be inserted is less than or greater than. as i progress down a side?
• 04-30-2010
iMalc
Yeah that's pretty much it. Make sure that you attach the node to the correct child of it's parent of course.
• 04-30-2010
Salem