C++树高度计算代码报Access violation reading location 0xFDFDFE01错误
错误原因
- 递归逻辑缺少空节点边界判断:当节点的左/右孩子值为
-1时,代码未做拦截直接将-1作为数组索引传入下一层递归,访问tree[-1]属于非法内存操作,直接触发访问越界错误,报错地址0xFDFDFE01是Windows调试堆的典型非法访问地址,符合越界访问的特征。 - 高度计算逻辑错误:非叶子节点的高度计算未加上当前层的1,即使解决越界问题也会得到错误的树高结果。
- 潜在风险:当前代码默认输入的节点编号(nd、father、child)和tree数组的下标
0~n-1完全对齐,如果输入的节点编号不满足该约定,也会出现数组越界问题。
解决方法
- 新增空节点边界判断:在High函数入口先判断传入的
headIndex是否为-1,如果是直接返回0(空节点高度为0)。 - 修正高度计算逻辑:非叶子节点的高度为左右子树最大高度加1。
- 可选优化:如果输入节点编号不保证和数组下标对齐,可新增哈希映射表将输入的节点编号转换为对应的数组下标,避免越界。
修正后的完整代码如下:
#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; } // 修正后的High函数 int High(int** tree, int headIndex) { // 新增空节点边界判断 if (headIndex == -1) { return 0; } 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) + 1; } int main(){ int** t = InputTree(); cout << High(t, 0); // 注意:使用完后需要释放new申请的内存,避免内存泄漏 system("pause>NULL"); return 0; }
内容的提问来源于stack exchange,提问作者Moataz Craft
相关产品推荐
相关产品推荐

