数据结构与算法(c#实现)系列—n叉树(一)
heavenkiller(原创)
n叉树的每一节点度数都相同,为n
using system;
using system.collections;
namespace datastructure
{
/// <summary>
/// narytree 的摘要说明。—–n叉树
/// </summary>
public class narytree:tree
{
// member variables
protected object key;
protected uint degree;
protected arraylist treelist=new arraylist();
//protected uint height=0;//暂时默认为0
//create an empty tree whose attribute of degree is _degree
public narytree(uint _degree)
{
//
// todo: 在此处添加构造函数逻辑
//
this.key=null;
this.degree=_degree;
this.treelist=null;
}
//构造一棵叶子结点的n叉树
public narytree(uint _degree,object _key)
{
this.key=_key;
this.degree=_degree;
this.treelist=new arraylist();
this.treelist.capacity=(int)_degree;
for(int i=0;i<this.treelist.capacity;i++)
{
this.treelist.add( this.getemptyinstance(_degree) );
}
}
//—————————————————————–
protected virtual object getemptyinstance(uint _degree)
{ return new narytree(_degree); }
//——————————————————————-
//judge whether the tree is an empty tree
public override bool isempty()
{ return this.key==null; }
//判定是否是叶子结点。如果即不是空树且每一棵子树均为空树,则为叶子结点
public override bool isleaf()
{
if(isempty())
return false;
for(uint i=0;i<this.degree;i++)
{
if( !(this[i].isempty()) )
return false;
}
return true;
}
//———————————–inherited attributes———————————
public override object key
{
get
{
return this.key;
}
}
//索引器
public override tree this[uint _index]
{
get
{
if( _index>=this.degree )
throw new exception("my:out of index!");//如果出界,则抛出异常
if( this.isempty() )
return null;//如果是空树,则索引器返回一个 null
return (tree)this.treelist[(int)_index];
}
set
{
this.treelist[(int)_index]=value;
}
}
