簡體   English   中英

如何拆分TreeList的子級

[英]How to split a TreeList's children

我一直在嘗試如何編寫TreeList,但是失敗了,所以我在Google上搜索了一個並從那里學不到。 那行得通,但是我現在想做的和找不到的是如何拆分TreeList。 我創建了2個示例,但都失敗了。 程序崩潰了。 我正在使用Java,而我所基於的TreeList類是http://yet-another-tree-structure.googlecode.com/svn/trunk/java/src/com/tree/

原創一本

public TreeNode<T> removeAndCreate() {
    TreeNode<T> tn = new TreeNode<T>(data);
    tn.children = children;
    tn.elementsIndex = elementsIndex;
    elementsIndex.remove(this);
    children.remove(this);
    return tn;
}

我正在使用較新的

public TreeNode<T> split() {
    TreeNode<T> tP = parent;
    while (tP.isRoot() == false) {
        tP = tP.parent;
    }
    TreeNode<T> tn = new TreeNode<T>(data);
    tn.children = children;
    tn.elementsIndex = elementsIndex;
    tP.elementsIndex.remove(this);
    tP.children.remove(this);
    return tn;
}

感謝您提前獲得的幫助。

在回顧了您所基於的類並進行了第二次拆分之后,我將假定拆分意味着將有問題的節點從當前樹中取出,並返回以該節點為根的新樹。 如果這是您要解決的問題,則需要修復一些問題。 首先,您的split函數執行以下操作:

TreeNode<T> tP = parent;
while (tP.isRoot() == false) {
    tP = tP.parent;
}

問題是,如果您當前的節點( this )沒有parent ,則會拋出Null異常(因此,嘗試拆分根節點,您將得到一個錯誤)。 我想你的意思是:

TreeNode<T> tP = this;

此更改將避免循環訪問可能為nullparent 接下來,您需要從parent級及更高級別刪除每個級別的所有elementsIndex 然后,您必須從直接parent刪除children (如果您有parent )。

我認為您可能正在尋找的代碼如下(假設我沒有錯過任何事情):

public TreeNode<T> split() {
    // Create a new root node for the tree we split off
    TreeNode<T> tn = new TreeNode<T>(data);
    tn.children = children;
    tn.elementsIndex = elementsIndex;

    // For each level of the tree above us make sure we remove
    // ourselves from the elementsIndex at EACH LEVEL until we
    // finish at the root.
    TreeNode<T> tP = this;
    while (tP.isRoot() == false) {
        tP = tP.parent;
        tP.elementsIndex.remove(this);
    }

    // If this node has a parent remove this node as one of
    // our parent's children. We aren't the child of any of the
    // levels above our parent
    if (parent != null)
        this.parent.children.remove(this);

    // Return the root of the newly split tree
    return tn;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM