我在一些算法上遇到了一些问题,这些算法应该返回树的最大度数(节点的最大子节点数)和深度(最长分支的维度)。看起来有些树结构可以工作,而有些则不能。有人可以告诉我我的代码是否有问题吗?
我的树结构是
public class Tree<T> {
public Node<T> root;
public Tree() {
root = null;
}
我的节点结构是:
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;
}
度数算法为:
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;
}
最后,深度算法:
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;
}
插入代码是:
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);
}
}
}
}
不工作的结构是:
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());
}
这返回 5 但应该返回 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());
}
这应该返回 3 但返回 2
e1 到 e7 是整数。