二叉树的建立及层次遍历(自下而上,自左而右输出)

给定一颗二叉树,要求从下至上按层遍历二叉树,每层的访问顺序是从左到右,每一层单独输出一行。
在这里插入图片描述
这道题目是数据结构初学者最头疼的题目之一。二叉树。c语言的灵魂和难点都在指针,而想要这里的二叉树实现的好,指针和链表的熟练运用必不可少,这题中还运用到了队列(环形队列)的知识,不熟悉的小伙伴可以去看一下这块的操作。ps:这两次被难哭了,艰难完成后心血来潮,希望能够借此造福后来人。第一次写博文,有问题的地方,希望大家多指教啦。

前言

这道题目其实用栈和二维数组来处理蛮简单的,不过既然考察二叉树和层次遍历,那还是按要求来好一些。这道题有几个比较难处理的点在于:

一、元素是int型数据而不是单个字符,也就是说需要考虑一个元素包含多于一位的数字(正整数)。

那这里我选择将整个字符串逐个字符读取并“转译”,把‘(’,‘)’,‘,’三种符号用-1,-2,-3来代替(因为元素都是正整数,所以不怕混淆)。其他部分的字符以字符串形式读取,每次当遇到‘(’,‘)’,‘,’,‘\n’标志着一个字串的结束,此时把这个字串用atoi函数转换成int数据,存入int数组中。遍历完成后,实现了字符串像字符数组的转译。

void String2Int(char str[])
{
	int i = 0;
	char temp[6];
	int x = 0;
	while (true)
	{
		
		
		if (str[i] == '(')
		{
			num[number++] = atoi(temp); memset(temp, '\0', sizeof(temp)); num[number++] = -1; x = 0;
		}
		else if (str[i] == ')')
		{
			if(temp[0]!='\0')num[number++] = atoi(temp); memset(temp, '\0', sizeof(temp)); num[number++] = -2; x = 0;
		}
		else if (str[i] == ',')
	





## 二、二叉树的创建
与其他经典二叉树的创建方式一样,数组中逐个数据读取后,通过条件语句选择合适的操作。这个步骤需要用到栈St(后进先出),当有括号嵌套时,总是能够保证由内到外,逐个完成链接。

```c
void CreateBTree(BTNode* &b)
{
	BTNode* St[MAXSIZE], * p=NULL;
	int top = -1, k=0, j = 0;
	int ch;
	b = NULL;
	ch = num[j];
	while (j<number)
	{
		switch (ch)
		{
		case -1:top++; St[top] = p; k = 1; break;
		case -2:top--; break;
		case -3:k = 2; break;
		default:p = (BTNode*)malloc(sizeof(BTNode));
			p->data = ch;
			p->left = p->right = NULL;
			if (b == NULL)
				b = p;
			else
			{
				switch (k)
				{
				case 1:St[top]->left = p; break;
				case 2:St[top]->right = p; break;
				}
			}
		}
		j++;
		ch = num[j];
	}
}

三、层次遍历

作为二叉树四种经典的遍历方式之一,需要用到环形队列,先进先出,每次把队头出队(deSqQueue),并把出队的元素的子节点从左到右依次入队(enSqQueue),该过程可以对出队元素增添一些需要的操作,故此可以实现层次遍历。但这还不够,因为我们这题要求分层并从最后一层开始输出。

四、从上到下层次遍历时如何实现分层,并按层数倒序输出

基本思路是创建一个二维数组,并将每一层放在同一维度中,难点在于遍历过程中难以确定在什么位置分层。有人讲可以根据深度判断,但个人感觉这样做的话完全就不需要二叉树,所以这样不太好。所以这里介绍一下动态分层的算法。
增加四个变量i(初始值为0),cur(初始值为1)表示当前层数应当容纳的元素数量,next(初始值为0)表示下一层应当容纳的元素数量,floor(初始值为0)表示层数。具体操作如下:

void LevelOrder(BTNode* b)
{
	BTNode* p;
	SqQueue* qu;
	InitQueue(qu);
	enQueue(qu, b);
	int i, cur, next;
	i = next = 0;
	cur = 1;
	while (qu->front<qu->rear)
	{
		p = (BTNode*)malloc(sizeof(BTNode));
		if (i < cur)
		{
			deQueue(qu, p);
			result[floor][i] = p->data;
			if (p->left != NULL)
			{enQueue(qu, p->left); next++;}
			if (p->right != NULL)
			{enQueue(qu, p->right); next++;}
			i++;
		}
		else
		{
			cur = next;
			i = 0;
			next = 0;
			floor++;
		}
	}

}

结果的输出

通过以上操作,最后从最后一层输出即可

完整代码如下

#define _CRT_SECURE_NO_WARNIGS
#include<stdio.h>
#include<string.h>
#include<malloc.h>
#include<stdlib.h>
#define MAXSIZE 200
int number = 0;
int floor = 0;
int print[100];
int result[10][20];
int num[MAXSIZE];
typedef struct node
{
	int data;
	struct node* left;
	struct node* right;
}BTNode;
typedef struct
{
	BTNode* data[MAXSIZE];
	int front, rear;
}SqQueue;
void String2Int(char str[])
{
	int i = 0;
	char temp[6];
	int x = 0;
	while (true)
	{
		
		
		if (str[i] == '(')
		{
			num[number++] = atoi(temp); memset(temp, '\0', sizeof(temp)); num[number++] = -1; x = 0;
		}
		else if (str[i] == ')')
		{
			if(temp[0]!='\0')num[number++] = atoi(temp); memset(temp, '\0', sizeof(temp)); num[number++] = -2; x = 0;
		}
		else if (str[i] == ',')
		{
			if(temp[0]!='\0')num[number++] = atoi(temp); memset(temp, '\0', sizeof(temp)); num[number++] = -3; x = 0;
		}
		else if (str[i] == '\0'||str[i]=='\n')
		{
			if(temp[0]!='\0')num[number++] = atoi(temp); break;
		}
		else
		{
			temp[x++] = str[i];
		}
		
		i++;
	}
}
void CreateBTree(BTNode* &b)
{
	BTNode* St[MAXSIZE], * p=NULL;
	int top = -1, k=0, j = 0;
	int ch;
	b = NULL;
	ch = num[j];
	while (j<number)
	{
		switch (ch)
		{
		case -1:top++; St[top] = p; k = 1; break;
		case -2:top--; break;
		case -3:k = 2; break;
		default:p = (BTNode*)malloc(sizeof(BTNode));
			p->data = ch;
			p->left = p->right = NULL;
			if (b == NULL)
				b = p;
			else
			{
				switch (k)
				{
				case 1:St[top]->left = p; break;
				case 2:St[top]->right = p; break;
				}
			}
		}
		j++;
		ch = num[j];
	}
}
void InitQueue(SqQueue*& qu)
{
	qu = (SqQueue*)malloc(sizeof(SqQueue));
	qu->front = qu->rear = 0;
}
bool enQueue(SqQueue*& q, BTNode* e)
{
	if ((q->rear + 1) % MAXSIZE == q->front)
		return false;
	q->rear = (q->rear + 1) % MAXSIZE;
	q->data[q->rear] = e;
	return true;
}
bool deQueue(SqQueue*& q, BTNode* &e)
{
	if (q->front == q->rear)
		return false;
	q->front = (q->front + 1) % MAXSIZE;
	e = q->data[q->front];
	return true;
}
bool QueueEmpty(SqQueue* q)
{
	return(q->front == q->rear);
}
void LevelOrder(BTNode* b)
{
	BTNode* p;
	SqQueue* qu;
	InitQueue(qu);
	enQueue(qu, b);
	int i, cur, next;
	i = next = 0;
	cur = 1;
	while (qu->front<qu->rear)
	{
		p = (BTNode*)malloc(sizeof(BTNode));
		if (i < cur)
		{
			deQueue(qu, p);
			result[floor][i] = p->data;
			if (p->left != NULL)
			{enQueue(qu, p->left); next++;}
			if (p->right != NULL)
			{enQueue(qu, p->right); next++;}
			i++;
		}
		else
		{
			cur = next;
			i = 0;
			next = 0;
			floor++;
		}
	}

}
int main()
{
	char str[MAXSIZE];
	
	BTNode* b=NULL;
	gets_s(str);
	String2Int(str);
	CreateBTree(b);
	LevelOrder(b);
	for (int i = floor; i >= 0; i--)
	{
		int j = 0;
		while (result[i][j] != '\0')
		{
			printf("%d ", result[i][j]);
			j++;
		}
		printf("\n");
	}
	return 0;
}

总结

一百多行一道题的数据结构代码对小白还是不太友好,这道题的重点需要有二叉树,栈,队的基本知识,除了最后倒序输出的小创新外,其他的算法都属于经典的基本操作,有问题可以查询数据结构的课本。总之作为第一次博文,还是有许多的不完美之处,希望大家多多指导哦。

  • 5
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

公子小白痴

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值