Data structures and algorithms (C # implementation) series --- tree (1)
Heavenkiller (original)
First, let's define the tree:
A tree is a finite, non-empty node set,
T = {r} or T1 or T2 or... Or Tn
It has the following properties:
1. the node r specified in the set is called the root node of the tree.
2. The remaining nodes can be divided into n subsets, T1, T2 ,... Tn (n> = 0), where each subset is a tree.
Other tree definitions, such as degree, leaf, and higher, are available everywhere.
One of the main features of a tree is traversal, which can be divided into deep traversal and breadth traversal.
Here, DepthFirstTravesal () and WidthFirstTravesal () are implemented respectively ()
Deep traversal is divided into pre-order traversal, middle-order traversal, and post-order traversal.
This is achieved by using the adapter technology.
Using System;
Using System. Collections;
Namespace DataStructure
{
/// <Summary>
/// Tree summary.
/// When traverse, traversaltype cant be changed, or throw a exception
/// Supports enumeration, comparison, and deep Replication
/// </Summary>
Public abstract class Tree: IEnumerable, IComparable
{
Public Tree ()
{
//
// TODO: add the constructor logic here
//
}
Protected Queue keyqueue = new Queue (); // It is used only for data storage during enumeration and is not used for comparison in Equals implementation.
Protected TraversalType traversaltype = TraversalType. Breadth; // choose a traversal type, and DepthFirst is default
// Protected uint degree = 0; // degree of the tree, init it as 0
// Protected uint height = 0; // height of the tree, init it as 0
// Enumerate different traversal types
Public enum TraversalType
{
Breadth = 1, // span Traversal
PreDepth = 2, // pre-order traversal
InDepth = 3, // traverse in the middle order
PostDepth = 4 // post-order traversal
};
// Public virtual abstract object Key {}
Public abstract Tree this [uint _ index] {get; set;} // if I only use get, can I change it later?
Public abstract object Key {get ;}
Public abstract uint Degree {get ;}
// Public abstract uint Height {get ;}
Public void SetTraversalType (TraversalType _ type) {traversaltype = _ type;} // set a traversal a type, if its not set manually, DepthFirst will be chosen in default
Public abstract bool IsEmpty (); // property takes the place of IsEmpty ()
Public abstract bool IsLeaf ();
// Only Visit, neednt queue
Public virtual void DepthFirstTraversal (IPrePostVisitor _ vis) // middle depthfirst traversal
{
// Use different visitors through _ vis to perform forward, backward, and central Traversal
If (! IsEmpty ())
{
_ Vis. PreVisit (this. Key );
If (this. Degree> = 1)
{
If (this. Degree> = 2)
{
For (uint I = 0; I <(this. Degree-1); I ++ )//
{
This [I]. DepthFirstTraversal (_ vis); // recursive call
// _ Vis. Visit (this. Key );
}
}
This [this. Degree-1]. DepthFirstTraversal (_ vis );
}
_ Vis. PostVisit (this. Key );
}