C++实现二叉树时preorder与postorder遍历输出错误问题求助
问题排查及修复方案
已定位的错误点
- 前序、后序遍历实现错误:两个函数内部递归时错误调用了中序
inorder方法,而非对应自身的递归方法,导致输出结果和预期遍历逻辑不符 - 节点计数
count函数错误:内部使用了静态变量x、y,静态变量在递归调用全程共用,不会随每次函数调用重置,导致计数结果异常 - 高度计算
height函数错误:一是内部错误调用了count函数统计子树高度,二是同样使用了静态变量a、b,导致高度计算结果错误
修复后的核心代码片段
// 修正后前序遍历 void preorder(struct node *yes) { if (yes != 0) { cout << "--> " << yes->data << endl; preorder(yes->left); preorder(yes->right); } } // 修正后后序遍历 void postorder(struct node *yes) { if (yes != 0) { postorder(yes->left); postorder(yes->right); cout << "--> " << yes->data << endl; } } // 修正后节点计数函数,移除静态变量 int count(struct node *yes) { if (yes == 0) return 0; int x = count(yes->left); int y = count(yes->right); return x + y + 1; } // 修正后高度计算函数,移除静态变量,递归调用自身 int height(struct node *yes) { if (yes == 0) return 0; int a = height(yes->left); int b = height(yes->right); if (a > b) return a + 1; else return b + 1; }
补充说明
队列逻辑本身没有问题,修复上述4个函数的错误后,遍历、节点计数、高度计算的输出结果即可符合预期。
内容的提问来源于stack exchange,提问作者Gautam Gupta
相关产品推荐
相关产品推荐

