TinyURL widget - shorten your URL's for free!

Enter a long URL to make tiny:

Tuesday, May 10, 2016

A real n-ary tree exemplar with GNodes from glib-2.XXX

This post presents a realistic GNodes unbalanced n-ary tree exemplar in C using Gnome glib-2.XXX.You can find more information on the API here.

I wanted to design a client/server node structuring system based on distance metric from a common point, so it made sense to explore  unbalanced trees. I wasn't familiar with them nor GLib at the outset. This work took about 2 days of fidgeting.

Online examples are bare presentations of the basic function calls. Here is a completed application that does something. The code you need is here ntree-distance.c.

This one presents an n-tree made from 3D Euclidean distances to and from an arbitrary point (city) and structures them on bounded distance neighbourhood balls. Essentially, the closest cities are siblings, those beyond a minimum metric are children, and those beyond a second metric are grandchildren. One could extend the paradigm as far as one likes.

The data for these cities is randomly generated, cities are then fed into a for loop that sorts them.  At the end of the code it uses the GLib g_tree_traverse and executes a simple printf function to display the data at each node.

In order to make children and grandchildren nodes at the start with no data entered, one can make notional child and grandchild nodes etc. to whatever depth is required. So in the code are a base, a middle, and a far (and a farthest I didn't include) GNode that are used to make a 4-depth tree structure before the data is available.

One important thing to note about GNodes is that there is a deep copy but no remove function. There is no direct way to remove a single child without destroying the rest under since the links are all pointers not a more complicated form of structure.  There is an unlink so one can construct a different tree from items but that may not be helpful.  Of course this means I have extra tree nodes at every level but I considered it as beneficial for my purpose because if in the future I removed other siblings I can maintain the tree skeleton as it were.

You will note in printouts the notional nodes appear as 0.0000 in the list for tree traversed so they are easy to pick out. As we append nodes at each level the notional tree elements are also 0 child so there is another way to ignore them.

Included in the gist github is a Makefile and the original notional GNode file from IBM that wasn't very helpful... like IBM...


I have included a copy of the old gnode.c code for examination, a glibtest.c from MIT I found if you need to sanity check your GLIB, a Makefile that will compile the ntree-distance.c and the glibtest.c  if you need them but the main file is ntree-distance.c