[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Make a random tree of generic TreeNode objects in C#

[Make a random tree of generic TreeNode objects in C#]

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 the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.