# Algorithm to print a tree

Hi all,

I am writing a plugin for Xojo and I am struggling to write the algorithm to accomplish the following (simple) task. Image a tree like this:

``````A0 B0 C0 D0 E0
|
C1 D1 E1
|
C2 D2
``````

Of course it is stored in a tree, where each node has a pointer to the parent and a vector of pointers to the childs (it is a multiway tree). Something like this:

``````struct Node {
Data          m_data;
Node*         m_prev;
vector<Node*> m_next;
}
``````

I would like to write an iterative Print function to write the tree like this:

``````A0 B0 C0
1: C1 D1 E1
2: C2 D2
D0 E0
``````

However I fail in correctly navigate trough the childs in case of multiple childs. Any suggestions?

Thank you very much.

Cheers,
Davide

ciao Davide (credo tu sia italiano).
Io ho dovuto fare una cosa simile, su volumi di dati comunque ridotti.
I miei dati stavano su un database e ho sfruttato questa entitĂ  (potresti usare un database Sqlite in memoria, creato a runtime).

Immagina una tabella â€śnodoâ€ť, contenente la colonna â€śpadreâ€ť. Fai una SELECT su tutti i record che hanno la colonna â€śpadreâ€ť NON valorizzata. Poi, in cascata, ricorsivamente, per ogni nodo X, cerchi i nodi che hanno come padre appunto X, e via dicendo, appunto in maniera ricorsiva.
Forse non Ă¨ molto efficiente, ma funziona

The keyword to search for ist â€śself referencedâ€ť. Iâ€™d suggest to make use of a self-referenced datasource, for instance a database table, where each record has a pointer to a parent (no need to reference the children). Then you make use of recursive functions to build nodes, sub-nodes, sub-sub-nodes and so forth.

Search for treeview recursion, treeview from a self referencing data table, and the like.
There used to be plenty of examples on the former Realbasic forum, now gone â€¦

I found an old sample project to build a tree recursively, from a database table:

Check out the load_tree and find_node methods in Window1. If you use Windows, then you will need to create a CopyFile BuildStep for the treeview.rsd Sqlite database file, for macOS it is already there.

A zip file with that Xojo project can be download from here:

EDIT: Requires the Einhugur TreeView control.

Check out the visitor pattern for tasks like this. Itâ€™s well explained in one of Bob Nystromâ€™s online books: Representing Code Â· Crafting Interpreters

1 Like

Thank you very much for all the suggestion. I will take a look at them.

That is a great link Garry - thanks!

That book is without a doubt the best programming book Iâ€™ve ever read by a country mile.

2 Likes