Java에서 최적 이진 검색 트리 문제를 구현하기 위해 노력하고 있습니다. 내 프로그램의 경우, 첫 번째 줄은 노드의 수이고 각 줄은 공백으로 구분되는 txt 파일에서 읽습니다. 첫 번째 요소는 노드이고 두 번째 요소는 확률입니다. 다음은 내 프로그램에서 읽고 샘플 입력 : 내 프로그램에서최적의 이진 검색 트리 구현을 사용하여 ArrayindexOutOfBoundsException java
5
A 0.213
B 0.547
D 0.10
X 0.12
AAA 0.02
, 나는 내가 프로그램을 실행할 때, 나는 그것의 가능성이 무엇인지, 그것이 무엇 노드 볼 수 있도록 인쇄 방법을 만들려고하고 있어요 , 그 부모는 무엇이며, 그들의 자녀는 무엇인가.
Node
Key: B
Probability: 21.3%
Parent: (null)
Left Child: A
Right Child: X
내가 지금으로 실행이 트리 미세의 루트를 읽고 있다는 것입니다하지만 잠시 후 나에게 밖으로 색인을 줄 것입니다 문제 : 한 노드의 출력 예제가 아래에 제공 범위. 다음은 내 코드를 실행할 때이 내가 수신하고 출력은
public static void printTree(String keys[], double prob[], int root[][]){
System.out.println("");
int pos = root[1][keys.length-1];
int t=pos;
for(int i = 0; i < keys.length-1; i ++){
System.out.println("Node Key "+ pos);
System.out.println("Key: "+ keys[pos]);
System.out.println("Probability: "+ prob[pos]);
if(i ==0){
System.out.println("Parent: null");
System.out.println("Left Child: "+ keys[pos-1]);
System.out.println("Right Child: "+ keys[pos+1]);
if(root[1][pos]==t){
pos-=1;
}
}
else{
System.out.println("Parent: "+ keys[pos+1]);
System.out.println("Left Child: "+ keys[pos-1]); //where the error is occurring
System.out.println("Right Child: "+ keys[pos+1]);
pos--;
}
System.out.println("");
}
}
내 인쇄 트리 방법에 대한 내 코드입니다 :
분명히Node
Key: B
B is the root
Node Key 2
Key: B
Probability: 0.547
Parent: null
Left Child: A
Right Child: D
Node Key 1
Key: A
Probability: 0.213
Parent: B
Left Child: null
Right Child: B
Node Key 0
Key: null
Probability: 0.0
Parent: A
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at OBST.printTree(OBST.java:62)
at OBST.main(OBST.java:155
내가 증가하고 크기를 감소 시도는하지만 여전히 그럴 때 IndexOutofBoundsException이 발생합니다. 나는 그 문제가 무엇인지를 믿는다. 그것은 루트를 읽는 것이고, 그 다음에는 목록을 내려 가서 멈추지 않는다.
누군가가이 문제에 대해 도움을 줄 수 있다면 매우 감사하겠습니다.
EDIT : 노드를 포함하도록 인쇄 방법을 재구성했지만 여전히 ArrayIndexOutofBoundsException이 발생합니다.
Node
Key: B
Probability: 0.547 %
Parent: B
A is the left child of B
Node
Key: B
Probability: 0.547 %
Parent: B
X is the right child of B
Node
Key: X
Probability: 0.12 %
Parent: X
D is the left child of X
Node
Key: X
Probability: 0.12 %
Parent: X
AAA is the right child of X
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at OptimalBT.Optimal.constructTree(Optimal.java:117)
at OptimalBT.Optimal.constructTree(Optimal.java:127)
at OptimalBT.Optimal.main(Optimal.java:90)
노드 키는 0으로 표시되고 노드 키는 pos의 값입니다. 그래서 pos는 0입니다. 키 [-1]과 같을 키 [- 1]를 할 때 어떤 배열 위치를 얻을 것으로 예상합니까? – Asthor
내 희망은 B의 오른쪽 자식 인 노드 4에 인쇄한다는 것입니다.하지만이 프로그램은 확률이 높고 아래로 내려 가고 있습니다. 그래서 만약 노드 2에서 시작한다면, 그 다음에 1 번 노드를 인쇄 한 다음 0과 – user2580