title: Iterative Binary Search Tree Insert in C
body: <p>This seems to be a simple question, and I have looked at another thread and it seems I am doing the same thing, however without results.</p>
  
  <p>This is my code to iteratively insert into a binary search tree, along with the structure and how to create a new node:</p>
  
  <pre><code>typedef struct node {
      int data;
      struct node *left;
      struct node *right;
  } node;
  
  node *create_node(int data) {
      node *n = calloc(1, sizeof(node));
  
      n-&gt;data = data;
      return n;
  }
  
  node *BST_insert_iterative(node *root, int data) {
      node *temp = root;
  
      if (root == NULL)
          return create_node(data);
  
      while (temp != NULL) {
          if (data &gt; temp-&gt;data)
              temp = temp-&gt;right;
          else
              temp = temp-&gt;left;
      }
  
      temp = create_node(data);
  
      return root;
  }
  </code></pre>
  
  <p>When I print the tree I only receive the first node:</p>
  
  <pre><code>Inserting 8  into BST...
  Inserting 50     into BST...
  Inserting 74     into BST...
  Inserting 59     into BST...
  Inserting 31     into BST...
  Inserting 73     into BST...
  Inserting 45     into BST...
  Inserting 79     into BST...
  Inserting 24     into BST...
  Inserting 10     into BST...
  In order traversal
  8
  Height of tree: 0
  </code></pre>
  
  <p>However, using the recursive insert function:</p>
  
  <pre><code>node *BST_insert(node *root, int data) {
      if (root == NULL)
          return create_node(data);
  
      if (root-&gt;data &gt;= data)
          root-&gt;left = BST_insert(root-&gt;left, data);
  
      else (root-&gt;data &lt; data)
          root-&gt;right = BST_insert(root-&gt;right, data);
  
      return root;
  }
  </code></pre>
  
  <p>it works just fine and I get:</p>
  
  <pre><code>Inserting 8  into BST...
  Inserting 50     into BST...
  Inserting 74     into BST...
  Inserting 59     into BST...
  Inserting 31     into BST...
  Inserting 73     into BST...
  Inserting 45     into BST...
  Inserting 79     into BST...
  Inserting 24     into BST...
  Inserting 10     into BST...
  In order traversal
  8
  10
  24
  31
  45
  50
  59
  73
  74
  79
  Height of tree: 4 
  </code></pre>