Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary Search Tree Insertion C without recursion

I am new to the page and I am really stuck at my university's homework to recreate a function that inserts nodes to the tree without Recursion. I have been given the Recursive method and I need to convert it to Iterative. This is the given Recursive Code:

TreeNode *InsertTree(TreeNode *root, TreeNode *newnode)
{
   if (!root)
   {
      root = newnode;
      root->left = root->right=NULL;
   }
   else if (newnode->entry < root->entry)
   {  
      root->left = InsertTree(root->left, newnode);
   }
   else
   {
      root->right = InsertTree(root->right, newnode);
   }
   return root;
}

and I made this one:

TreeNode *InsertTree(TreeNode *root, TreeNode *newnode)
{
   if (!root)
   {
      root = newnode;
      root->left = root->right=NULL;
   }  
   else 
   {
      TreeNode * temp = root, *prev = NULL;

      while(temp)
      {
        if (temp->entry < newnode->entry)
          temp = temp->right;
        else
          temp = temp->left;
      }
      newnode;
      temp->left = temp->right = NULL;
   }
   return root;
}

it works for the first elements but it doesn't save the rest elements. Any ideas? Thanks in advance

like image 873
Ilias Mentz Avatar asked May 25 '26 12:05

Ilias Mentz


1 Answers

The (un)usage of prev indicates the awareness that the recursive results need to be patched. As already a solution is given by others, here the "ideal" solution, using pointer aliases.

   TreeNode **current = &root;
   while (*current)
   {
       if (newnode->entry < (*current)->entry)
       {
           current = &(*current)->left;
       }
       else
       {
           current = &(*current)->right;
       }
   }
   *current = newnode;
   newnode->left = newnode->right = NULL;
   return root;

current will at the end point to root, or a left/right of a node; being null.

Note that this usage of aliases does not exist in some other languages like java. One of the very few advantages of C.

The & prefix-operator takes the address of the variable.

like image 185
Joop Eggen Avatar answered May 28 '26 03:05

Joop Eggen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!