title: c, greatest integer less than k
body: <p>Given a number and a binary tree, find the greatest number in the node less than k.</p>
  
  <p>The function I used looks like:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  //A binary tree with a pointer to the left and right child
  struct node
  {
      int data;
      struct node *left;
      struct node *right;
  };
  
  // function to allocate new node
  struct node* newNode(int data)
  {
      struct node* node = (struct node*)malloc(sizeof(struct node));
      node-&gt;data = data;
      node-&gt;left = node-&gt;right = NULL;
      return (node);
  }
  
  int findNum (struct node* root, int K)
  {
      int val = K;
  
      while( root )
          if( root-&gt;data &gt;= K )
              root = root-&gt;left;
          else{
              val = root-&gt;data;
              root = root-&gt;right;
          }
  
      return val;
  }
  
  int main()
  {
      struct node *root = newNode(9);
      root-&gt;left = newNode(13);
      root-&gt;right = newNode(10);
      root-&gt;right-&gt;right= newNode(20);
      root-&gt;left-&gt;left  = newNode(8);
      root-&gt;left-&gt;right = newNode(4);
      root-&gt;right-&gt;right-&gt;left = newNode(3);
      root-&gt;right-&gt;right-&gt;right = newNode(18);
  
      printf("%d", findNum(root,21));
      return 0;
  }
  </code></pre>
  
  <p>The output in this case should have been 20, but it outputs 18. The program isn't working, what have I done wrong?</p>