2021-11-06

这段代码展示了如何使用C++实现二叉树的四种遍历方式:先序、中序、后序和层次遍历。用户通过输入节点创建完全二叉树,然后程序输出各遍历结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// 二叉树.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#define _CRT_SECURE_NO_WARNINGS

#include <iostream>
#include"stdlib.h"
#include"string.h"
#include"conio.h"

typedef struct node
{
	char data;
	struct node* lc;
	struct node* rc;
}MYTREE, * PMYTREE;

void preorder(PMYTREE root, char* out);
void inorder(PMYTREE root, char* out);
void postorder(PMYTREE root, char* out);
void levelorder(PMYTREE root, char* out);

int main()
{
	PMYTREE root = NULL;
	PMYTREE s;
	PMYTREE Q[128];
	int front = 1, rear = 0;
	char temp[128], * p;
	printf("请按照完全二叉树格式输入节点,空间用@代替,逗号间隔:");
	scanf_s("%s", temp, 128);
	p = temp;
	while (strlen(p) > 0)
	{
		s = NULL;
		if (*p != '@')
		{
			s = (PMYTREE)malloc(sizeof(MYTREE));
			s->data = *p;
			s->lc = NULL;
			s->rc = NULL;
		}
		rear++;
		Q[rear] = s;
		if (rear == 1)
			root = s;
		else
		{
			if (s != NULL && Q[front] != NULL)
			{
				if (rear % 2 == 0)
					Q[front]->lc = s;
				else
					Q[front]->rc = s;
			}
			if (rear % 2 == 1)
				front++;
		}
		if (strlen(p) > 1)
			p = p + 2;
		else
			p = p + 1;
	}
	printf("二叉树已经成功创建\r\n");
	memset(temp, 0, 128);
	preorder(root, temp);
	printf("先序遍历结果为:%s\r\n", temp);
	memset(temp, 0, 128);
	inorder(root, temp);
	printf("中序遍历结果为:%s\r\n", temp);
	memset(temp, 0, 128);
	postorder(root, temp);
	printf("后序遍历结果为:%s\r\n", temp);
	memset(temp, 0, 128);
	levelorder(root, temp);
	printf("层次遍历结果为:%s\r\n", temp);
	return 0;
}
void preorder(PMYTREE root, char* out)//先序遍历
{
	if (root != NULL)
	{
		sprintf(out, "%s%c", out, root->data);
		preorder(root->lc, out);
		preorder(root->rc, out);
	}
}
void inorder(PMYTREE root, char* out)//中序遍历
{
	if (root != NULL)
	{
		inorder(root->lc, out);
		sprintf(out, "%s%c", out, root->data);
		inorder(root->rc, out);
	}
}
void postorder(PMYTREE root, char* out)//后序遍历
{
	if (root != NULL)
	{
		postorder(root->lc, out);
		postorder(root->rc, out);
		sprintf(out, "%s%c", out, root->data);
	}
}
void levelorder(PMYTREE root, char* out)//层次遍历
{
	PMYTREE Q[128], s;
	int front = 0, rear = 0;
	Q[rear++] = root;
	while (rear > front)
	{
		printf(out, "%s%c", out, Q[front]->data);
		s = Q[front++];
		if (s->lc != NULL)
			Q[rear++] = s->lc;
		if (s->rc != NULL)
			Q[rear++] = s->rc;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值