這是整個代碼,我沒有使用頭檔案這個代碼必須輸入一個樹然后寫出它的高度,問題出High()在該行的函式中if (tree[headIndex][1] == -1 && tree[headIndex][2] == -1) {,它說:
Access violation reading location 0xFDFDFE01.
#include<iostream>
using namespace std;
int** InputTree() {
int n, nd, father;
int child;
char dir;
std::cin >> n;
int** tree = new int* [n];
for (int i = 0; i < n; i ) {
std::cin >> nd;
tree[i] = new int[3];
tree[i][0] = nd;
tree[i][1] = -1;
tree[i][2] = -1;
}
for (int i = 0; i < n - 1; i ) {
std::cin >> father >> child >> dir;
if (dir == 'L')
tree[father][1] = child;
else
tree[father][2] = child;
}
return tree;
}
int High(int** tree, int headIndex) {
if (tree[headIndex][1] == -1 && tree[headIndex][2] == -1) {
return 1;
}
int high1 = High(tree, tree[headIndex][1]);
int high2 = High(tree, tree[headIndex][2]);
return (high1 > high2 ? high1 : high2);
}
int main(){
int** t = InputTree();
cout << High(t, 0);
system("pause>NULL");
return 0;
}
uj5u.com熱心網友回復:
High可以使用headIndex等于 -1來呼叫遞回呼叫。您的遞回僅在兩個子節點都為 -1 時停止,但如果其中一個為 -1 而另一個指向另一個節點,您將進行遞回呼叫并取消參考越界索引。
解決此問題的一種方法是在進行遞回呼叫之前檢查每個節點,例如:
int high1 = tree[headIndex][1] == -1 ? 1 : High(tree, tree[headIndex][1]);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/364651.html
