I am having some problems with several algorithms that should return the maximum degree (maximum number of node children) and the depth (size of the longest branch) of the tree. It seems that they work with some tree structures, and some others do not. Can someone please tell me that I am doing something wrong with the code?
My tree structure
public class Tree<T> {
public Node<T> root;
public Tree() {
root = null;
}
My Node Structure:
public class Node<T>{
public T elem;
private Node<T> father;
private Node<T> child;
private Node<T> sibling;
private T epsilon;
public Node(T elem){
this.elem = elem;
this.father = null;
this.child = null;
this.sibling = null;
}
Degree Algorithm:
public int degree(){
int breadth = 0;
int max = 0;
return auxDegree(this.root, breadth, max);
}
public int auxDegree(Node<T> node, int count, int maxChild){
if(node!=null){
if(node.getChild()!=null){
maxChild = Math.max(auxDegree(node.getChild(), 0, maxChild), auxDegree(node.getSibling(), 0, maxChild));
count = countSibling(node.getChild()) + 1;
return (count>maxChild) ? count : maxChild;
}else return maxChild;
}else return maxChild;
}
Finally, the depth algorithm:
public int depth(){
int deepness = 0;
return auxDepth(this.root, deepness);
}
public int auxDepth(Node<T> node, int maxDepth){
if(node!=null){
if(node.getChild()!=null){
maxDepth = Math.max(maxDepth, auxDepth(node.getChild(), maxDepth));
maxDepth = maxDepth + 1;
return maxDepth;
}else{
return maxDepth;
}
}else return maxDepth;
}
Insert Code:
public Node<T> search(T key){
return searchAux(this.root, key);
}
private Node<T> searchAux(Node<T> node, T key){
if(node == null)
return null;
else{
while(node.getChild() != null && key != node.getElem()){
node = node.getChild();
searchAux(node.getSibling(), key);
}
}
return node;
}
public void insert(T father_key, T child_key){
if(IsEmpty())
this.root = new Node<T>(child_key);
else{
Node<T> node = new Node<T>(child_key);
Node<T> father = search(father_key);
if(father.getChild() == null){
father.setChild(node);
node.setParent(father);
}else{
if (father.getChild() != null){
Node<T> brother = father.getChild();
while(brother.getSibling() != null){
brother = brother.getSibling();
}
brother.setSibling(node);
node.setParent(father);
}
}
}
}
Structure that does not work:
public void Test_Depth(){
tree.insert(null, e2);
tree.insert(e2, e3);
tree.insert(e2, e1);
tree.insert(e3, e4);
tree.insert(e4, e5);
tree.insert(e5, e6);
tree.insert(e6, e7);
assertEquals(6,tree.depth());
}
This returns 5, but should return 6
public void Test_Depth(){
tree.insert(null, e1);
tree.insert(e1, e2);
tree.insert(e1, e3);
tree.insert(e3, e4);
tree.insert(e3, e5);
tree.insert(e3, e6);
assertEquals(3,tree.degree());
}
This should return 3, but returns 2
e1 - e7 are integers.