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.
After reviewing the classes you based things on and your second split I am going to assume that split means to take the node in question out of the current tree and return a new tree with node in question as its root. If that is what you are after then a few things need fixing. First of all your split
function does:
TreeNode<T> tP = parent;
while (tP.isRoot() == false) {
tP = tP.parent;
}
Problem is that if your current node (this
) doesn't have a parent
you will get a Null exception thrown (so try splitting the root node and you should get an error). I think you meant:
TreeNode<T> tP = this;
This change will avoid the loop accessing a parent
that may be null
. Next, you need to delete all the elementsIndex
at each level from the parent
and above. You then have to remove the children
from your direct parent
(if you have a parent
).
I think the code you might be looking for is below (assuming I haven't missed something):
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;
}