트리의 최대 차수 (노드의 최대 수)와 깊이 (가장 긴 분기의 길이)를 반환해야하는 몇 가지 알고리즘에 몇 가지 문제가 있습니다. 일부 나무 구조에서는 작동하지만 일부에서는 그렇지 않습니다. 누군가 내가 코드에 문제가 있는지 말해 줄 수 있습니까?N 진 트리 깊이 및 차수 알고리즘
내 트리 구조는
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());
}
이이 3 만 수익률을 반환해야 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());
}
를 반환해야 2
e1 내지 e7은 정수이다.
"나쁜"및 "좋은"트리 구조를 제공하는 것이 문제를 분석하는 데 도움이 될 것 같아요. – Picard
나는 그들을 추가했다. 죄송합니다. 문제는, 그것들은 두 명과 두 명을 제외하고 시도한 거의 모든 것에서 작동합니다. – Leo
삽입 (...) 구현을 보여줄 수 있습니까? –