title: How to efficiently find last key and value in GTree
body: <p>I need to develop a set of functions to extend <code>glib2</code> <code>GTree</code> with:</p>
  
  <ul>
  <li>find first element</li>
  <li>find last</li>
  <li>find nearest (floor, ceil, greatest less than, least greater than)</li>
  </ul>
  
  <p>Finding first is easy. You simply stop the <code>g_tree_foreach()</code> calback after first. But how to find the last element <strong>without traversing the whole tree</strong>?</p>
  
  <p>I thought I could use <code>g_tree_search()</code> with a callback that keeps returning a positive value until found, but how do I know I'm currently on the last element?</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;string.h&gt;
  
  #include &lt;glib.h&gt;
  
  static
  gint compare_int(gconstpointer p1, gconstpointer p2) {
      int i1 = GPOINTER_TO_INT(p1);
      int i2 = GPOINTER_TO_INT(p2);
      //printf("%d %d\n", i1, i2);
      return i1 == i2 ? 0 : i1 &gt; i2 ? 1 : -1;
  }
  
  
  static
  gboolean traverse(gpointer key, gpointer value, gpointer data) {
      //int ikey = GPOINTER_TO_INT(key);
      const char *sval = (const char *)value;
      printf("%s\n", sval);
      return FALSE;
  }
  
  static
  gint find_last(gconstpointer p, gpointer user_data) {
      return 1;
  }
  
  static inline const char *NULS(const char *s) {
      return s ? s : "NULL";
  }
  
  int main(int argc, char *argv[]) {
      GTree *tree = g_tree_new(compare_int);
      g_tree_insert(tree, GINT_TO_POINTER(10), "ten");
      g_tree_insert(tree, GINT_TO_POINTER(-99), "minus ninety-nine");
      g_tree_insert(tree, GINT_TO_POINTER(8), "eight");
      g_tree_foreach(tree, traverse, NULL);
      printf("=======\n%s\n", NULS((const char*)g_tree_search(tree, (GCompareFunc)find_last, NULL)));
      return 0;
  }
  </code></pre>