Make a random tree of generic TreeNode objects in C#

[random tree]

The example Handle generic TreeNode mouse events in C# explains how to build a tree where each node is represent by a TreeNode object. Each TreeNode contains its own object that determines how the node is drawn. This example the previous one to draw random trees.

The idea is simple. The program adds the tree’s nodes to a list. When it needs to add a new node to the tree, it picks a random node from the list to be the new node’s parent.

When the program starts, it uses the following code to build the random tree.

// The root node.
private TreeNode<CircleNode> Root;

// Make a tree.
private void Form1_Load(object sender, EventArgs e)
{
    // Make a list of all nodes.
    List<TreeNode<CircleNode>> nodes =
        new List<TreeNode<CircleNode>>();

    // Make the root node.
    Root = new TreeNode<CircleNode>(new CircleNode("Root"));
    nodes.Add(Root);

    // Make random child nodes.
    Random rand = new Random();
    for (char letter = 'A'; letter <= 'Z'; letter++)
    {
        // Make a new node.
        TreeNode<CircleNode> new_node =
            new TreeNode<CircleNode>(new CircleNode(letter.ToString()));

        // Pick a random parent node.
        int i = rand.Next(0, nodes.Count - 1);

        // Add the new node to the parent's children.
        nodes[i].AddChild(new_node);

        // Add the new node to the nodes list.
        nodes.Add(new_node);
    }

    // Arrange the tree.
    ArrangeTree();
}

This code declares the Root variable at the class level outside of any methods.

The form’s Load event handler creates a list of TreeNode objects named nodes. This list will hold references to all of the tree’s nodes.

Next the code creates the root node and adds it to the nodes list. It then loops over the letter A to Z. For each letter it creates a new node to display that letter. It then uses a Random object to pick a random index in the nodes list. It adds the new node to the children of the randomly selected node. It also adds the new node to the nodes list so it might have children later.

After it has finished building the tree, the event handler calls the ArrangeTree method just as the previous version of the program does.

The rest of the program is the same as the previous version. Download the example and see the previous post to see details such as how the program lays out and draws the tree.


Download Example   Follow me on Twitter   RSS feed   Donate




About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in classes, generic, OOP and tagged , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.