Tag Archives: tree implementation

Tree and Tree node implementation

A tree is a very useful structure, many people like to use

class TreeNode{
E nodeData;
TreeNode child1;
TreeNode child2;
...
}

to represent nodes in a tree, I find it complicated and hoping to get create a way such that tree nodes can be any class that implement a TreeNode class. For example, anytime you try to get the child or parent, you'll have to throw away this wrapper of TreeNode. The code in my mind to use the node would be as easy as
class employee implements TreeNode{
...
}
Then we can use
employee e1= new employee();
employee e2= new employee();
e2.addChild(e1);

But this bring up a problem. The tree node function such as, getChildren, getParent, getDecendants, they should be inherited instead of re-declared in each of the subclass that implements TreeNode.
So a better way is to use abstract class instead of interface.
public abstract class Treenode<T extends Treenode<T>> {
T next;
T myself=(T) this;
T parent;
public void addChild(T node) {
next=node;
node.parent=myself;
}
public T getChild() {
return next;
}
public T getParent(){
return parent;
}

}
The logic here is that any class that extends this Treenode class will automatically get the following functions without reprogramming them. The ugly part of this snippet is the T myself=(T) this;. Here the "this" is considered to be any Treenode, but myself is considered to be the subclass that extends it. This have to be a cast, but I can't see any reason such a cast could fail. Unless
class class1 extends Treenode{};
class class2 extends Treenode{};

Then for some reason you want

class1 c=new class1();
c.add(new class2());

This should not happen as a strongly typed programming practice. Period.