0

I have been trying how to write a TreeList but failed so I googled one up and learn't from there. That works but what I am now trying to do and what I cannot find is how to split a TreeList. I have created 2 examples and both have failed me. The program just crashes. I am using Java and the TreeList class I am basing of is http://yet-another-tree-structure.googlecode.com/svn/trunk/java/src/com/tree/.

Original one

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

The newer one I am using

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

I thank you for the help I receive in advance.

4

1 回答 1

0

在查看了您所基于的类和您的第二次拆分之后,我将假设拆分意味着将有问题的节点从当前树中取出并返回一个新树,其中有问题的节点作为其根。如果这就是你所追求的,那么一些事情需要修复。首先你的split功能是:

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

问题是,如果您的当前节点 ( this) 没有 aparent您将抛出 Null 异常(因此尝试拆分根节点,您应该会收到错误)。我想你的意思是:

TreeNode<T> tP = this;

此更改将避免循环访问parent可能是null. 接下来,您需要从上述及以上删除elementsIndex每个级别的所有内容。然后,您必须从直接parent删除(如果您有)。childrenparentparent

我认为您可能正在寻找的代码如下(假设我没有错过任何东西):

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;
}
于 2014-09-13T08:10:03.827 回答