title: Binary Search Tree in C
body: <p>I'm a Python guy. Learning C language and I've been trying to implement Binary Search Tree in C. I wrote down the code, and I've been trying from few hours but, not able to get the output as expected. Please help!</p>
  
  <p>Please correct me.</p>
  
  <pre><code>#include&lt;stdlib.h&gt;
  #include&lt;stdio.h&gt;
  
  typedef int ElementType;
  
  typedef struct TreeNode {
    ElementType element;
    struct TreeNode *left, *right;
  } TreeNode;
  
  TreeNode *createTree(){
      //Create the root of tree
      TreeNode *tempNode;
      tempNode = malloc(sizeof(TreeNode));
      tempNode-&gt;element = 0;
      tempNode-&gt;left = NULL;
      tempNode-&gt;right = NULL;
      return tempNode;
  }
  
  TreeNode *createNode(ElementType X){
      //Create a new leaf node and return the pointer
      TreeNode *tempNode;
      tempNode = malloc(sizeof(TreeNode));
      tempNode-&gt;element = X;
      tempNode-&gt;left = NULL;
      tempNode-&gt;right = NULL;
      return tempNode;
  }
  
  TreeNode *insertElement(TreeNode *node, ElementType X){
      //insert element to Tree
      if(node==NULL){
          return createNode(X);
      }
      else{
          if(X &lt; node-&gt;element){
              node-&gt;left = insertElement(node-&gt;left, X);
          }
          else if(X &gt; node-&gt;element){
              node-&gt;right =  insertElement(node-&gt;right, X);
          }
          else if(X == node-&gt;element){
              printf("Oops! the element is already present in the tree.");
          }
      }
  }
  
  TreeNode *displayTree(TreeNode *node){
      //display the full tree
      if(node==NULL){
          return;
      }
      displayTree(node-&gt;left);
      printf("| %d ", node-&gt;element); 
      displayTree(node-&gt;right);
  }
  
  main(){
      //pointer to root of tree #2
      TreeNode *TreePtr;
      TreeNode *TreeRoot;
      TreeNode *TreeChild;
  
      //Create the root of tree
      TreePtr = createTree();
  
      TreeRoot = TreePtr;
  
      TreeRoot-&gt;element = 32;
      printf("%d\n",TreeRoot-&gt;element);
  
      insertElement(TreeRoot, 8);
      TreeChild = TreeRoot-&gt;left;
      printf("%d\n",TreeChild-&gt;element);  
  
      insertElement(TreeRoot, 2);
      insertElement(TreeRoot, 7);
      insertElement(TreeRoot, 42);
      insertElement(TreeRoot, 28);
      insertElement(TreeRoot, 1);
      insertElement(TreeRoot, 4);
      insertElement(TreeRoot, 5);
  
  // the output is not as expected :(
      displayTree(TreeRoot);
  }
  </code></pre>