Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

10.7. Creating an n-ary Tree

Problem

You need a tree that can store a number of child nodes in each of its nodes. A binary tree would work if each node needs to have only two children, but, in this case, each node needs to have a fixed number of child nodes greater than two.

Solution

Use the following NTree class to create the root node for the n-ary tree:

using System;
using System.Collections;

public class NTree
{
    public NTree( ) 
    {
        maxChildren = int.MaxValue;
    }

    public NTree(int maxNumChildren) 
    {
        maxChildren = maxNumChildren;
    }

    // The root node of the tree
    protected NTreeNodeFactory.NTreeNode root = null;
    // The maximum number of child nodes that a parent node may contain
    protected int maxChildren = 0;

    public void AddRoot(NTreeNodeFactory.NTreeNode node)
    {
        root = node;
    }

    public NTreeNodeFactory.NTreeNode GetRoot( )
    {
        return (root);
    }

    public int MaxChildren
    {
        get {return (maxChildren);}
    }
}

The methods defined in Table 10-6 are of particular interest to using an NTree object.

Table 10-6. Members of the NTree class

Member

Description

Overloaded constructor

This constructor creates an NTree object. Its syntax is:

NTree(int maxNumChildren)

where maxNumChildren is the maximum number of children that one node may have at any time.

MaxChildren property

A read-only property to retrieve the maximum number of children any node may have. Its syntax is:

int MaxChildren {get;}

The value this property returns is set in the constructor.

AddRoot method

Adds a node to the tree. Its syntax ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata