在您提供的代码中,遍历结果不正确的原因是,在递归遍历函数中,对左子树和右子树的遍历调用时,使用了错误的函数名。以下是修改后的代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct BinaryNode {
char ch;
struct BinaryNode* lchild;
struct BinaryNode* rchild;
};
// 先序遍历
void recursionFirst(struct BinaryNode* root) {
if (root == NULL) {
return;
}
printf(" %c", root->ch);
recursionFirst(root->lchild);
recursionFirst(root->rchild);
}
// 中序遍历
void recursionMid(struct BinaryNode* root) {
if (root == NULL) {
return;
}
recursionMid(root->lchild);
printf(" %c", root->ch);
recursionMid(root->rchild);
}
// 后序遍历
void recursionLast(struct BinaryNode* root) {
if (root == NULL) {
return;
}
recursionLast(root->lchild);
recursionLast(root->rchild);
printf(" %c", root->ch);
}
void test01() {
struct BinaryNode nodeA = { 'A',NULL,NULL };
struct BinaryNode nodeB = { 'B',NULL,NULL };
struct BinaryNode nodeC = { 'C',NULL,NULL };
struct BinaryNode nodeD = { 'D',NULL,NULL };
struct BinaryNode nodeE = { 'E',NULL,NULL };
struct BinaryNode nodeF = { 'F',NULL,NULL };
struct BinaryNode nodeG = { 'G',NULL,NULL };
struct BinaryNode nodeH = { 'H',NULL,NULL };
nodeA.lchild = &nodeB;
nodeA.rchild = &nodeF;
nodeB.rchild = &nodeC;
nodeC.lchild = &nodeD;
nodeC.rchild = &nodeE;
nodeF.rchild = &nodeG;
nodeG.lchild = &nodeH;
// 递归遍历
printf("先序遍历:");
recursionFirst(&nodeA);
printf("\n");
printf("中序遍历:");
recursionMid(&nodeA);
printf("\n");
printf("后序遍历:");
recursionLast(&nodeA);
printf("\n");
}
int main() {
test01();
return 0;
}
在修正后的代码中,递归函数的调用已经修改正确,并且输出结果将会是正确的先序、中序和后序遍历结果。请重新运行代码并检查输出。
内容由零声教学AI助手提供,问题来源于学员提问




