ZBLOG

#include #include #include struct BinaryNode { //数据域 char ch; //指针域 struct BinaryNode* lchild; struct BinaryNode* rchild; }; //先序遍历 void recursionFirst(struct BinaryNode *root) { if (root==NULL) { return; } p...

在您提供的代码中,遍历结果不正确的原因是,在递归遍历函数中,对左子树和右子树的遍历调用时,使用了错误的函数名。以下是修改后的代码:

#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助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=13145

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?