Binary Search Tree Insertion C without recursion

11,916

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.

Share:
11,916
Ilias Mentz
Author by

Ilias Mentz

By Day: Software Engineer By Night: Kick-boxing athlete

Updated on June 04, 2022

Comments

  • Ilias Mentz
    Ilias Mentz almost 2 years

    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

  • Admin
    Admin about 8 years
    A ( is missing in the second to last line of your code.
  • Ilias Mentz
    Ilias Mentz about 8 years
    @JoopEggen That is working perfect thank you very much for help!