Skip to content

Tree

The Trie<T> class allows you to create acyclic dependency graphs that start from a root node and end with leaf nodes. A single node can have an unlimited number of branches.

Each node of the tree is identified by a string id, which must be unique among the children of the same parent, and holds a value of type T. The Trie<T> class is both the tree and the node class. So any child of a tree returns a tree object too.

To create a tree, first create an empty root node using Trie<T>.Create(), where T is the value type of the nodes. Then, add new nodes using the AddChild(...) method. For example, to create a tree of game objects:

public class MyComponent : MonoBehaviour
{
    public GameObject characters;
    public GameObject player;
    public GameObject enemy;

    private void Awake()
    {
        // Create the root node:
        Trie<GameObject> root = Trie<GameObject>.Create();

        // Add elements:
        Trie<GameObject> group = new Trie<GameObject>("characters", this.characters);
        root.AddChild(group);

        group.AddChild(new Trie<GameObject>("player", this.player));
        group.AddChild(new Trie<GameObject>("enemy", this.enemy));

        foreach (Trie<GameObject> child in group)
        {
            // Print child id:
            Debug.Log(child.id);

            // Print child game object:
            Debug.Log(child.Data.name);
        }
    }
}

Iterating over a tree using foreach returns its direct children. The AddChild(...) method returns the node that has been added, or null if the parent already had a child with the same id.

A node can return its parent:

Trie<GameObject> parent = group.Parent;

And its children, which is a dictionary indexed by their ids:

Dictionary<string, Trie<GameObject>> children = group.Children;

Debugging a Tree

Calling ToString() on a node returns the text representation of the whole branch that starts from it, which is very useful for printing the structure of the tree on the console.