N 元樹節點類別核心成員實作(續上篇):
public override uint Degree {
get { return this.degree; }
}
// 僅用於空節點
public virtual void AttachKey(object _obj) {
if (!IsEmpty()) throw new Exception("節點必須為空樹節點!");
this.key = _obj;
this.treeList = new ArrayList();
this.treeList.Capacity = (int)this.degree;
for (int i = 0; i < this.degree; i++)
treeList.Add(new NaryTree(this.degree));
}
// 僅用於葉子節點,移除關鍵字並回傳
public virtual object DetachKey() {
if (!IsLeaf()) throw new Exception("節點必須為葉子節點!");
object result = this.key;
this.key = null;
this.treeList = null;
return result;
}
// 連接子樹到第 num 個位置
public virtual void AttachSubtree(uint num, NaryTree _naryTree) {
if (this.IsEmpty()) throw new Exception("不能是空樹!");
if (!this[num - 1].IsEmpty() || this.degree != _naryTree.degree)
throw new Exception("目標位置必須為空且度數相同!");
this[num - 1] = _naryTree;
}
// 移除第 num 棵子樹並換上空樹
public virtual NaryTree DetachSubtree(uint num) {
if (IsEmpty()) throw new Exception("不能是空樹!");
NaryTree tmpTree = this;
((NaryTree)this[num - 1]).key = null;
((NaryTree)this[num - 1]).treeList = null;
return this;
}
提供節點關鍵字掛載/移除、子樹連接/拆離等核心操作,嚴格檢查前置條件(空節點、葉子節點、度數一致)確保樹結構完整性。