首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

資料結構與演算法:C# 實作 N 元樹 (下)

     編輯:關於C語言

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;
}

提供節點關鍵字掛載/移除、子樹連接/拆離等核心操作,嚴格檢查前置條件(空節點、葉子節點、度數一致)確保樹結構完整性。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved