Computer Science & C Programming


C Programming

Trees are an example of "recursive" structure and can be manipulated by the way of recursive programs/functions.

#define MAXI 3

gboolean prn(GNode* node, gpointer data) {
  if(node->data!=NULL) {
    g_print(((GString*)node->data)->str);
    g_print(" ");
  }
  return 0;
}

GNode* build(GString* val, char deep) {
  GNode* node = g_node_new(val);
  if (deep>0) {
    for (int i=0; i<MAXI; i++) {
      GString* newval = g_string_new(val->str); // copy
      g_string_append_c(newval,i+'0'); // 0 to '0'
      g_node_append(node,build(newval,deep-1));
    }
  }
  return node;
}

void main() {
  GNode* root = build(g_string_new(""),MAXI);
  g_node_traverse(root, G_LEVEL_ORDER, G_TRAVERSE_LEAVES,-1,prn,NULL);
}