自下而上、从右往左层次遍历

这篇博客详细介绍了如何实现二叉树的自下而上、从右到左的层次遍历算法。通过结合栈和队列的数据结构,先将节点入队,然后出队并入栈,最后按顺序访问栈中的节点来达到目标遍历顺序。示例代码展示了整个过程,包括创建栈、队列、节点以及遍历函数的实现。

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

试给出二叉树的自下而上、从右到左的层次遍历算法
    分析:
        我们只需要在层次遍历的基础上加入栈的使用,我们每次出队后的数据将其入栈,队列空了时,再去依次访问栈中元素,即可达到要求
代码如下:

struct biTree {
	char data;
	struct biTree *lchild;
	struct biTree *rchild;
};
struct Squeue {
	biTree *arr;
	int front, rear;
};
struct Stack {
	biTree *arr;
	int len;
	int top;
};
#include <stdio.h>
#include <stdlib.h>
void levelOrder2(biTree *T, Squeue *sq, int maxSize) {
	struct Stack *s = (struct Stack *)malloc(sizeof(struct Stack));
	struct biTree *p = T;
	struct biTree *r = (struct biTree *)malloc(sizeof(struct biTree));
	bool enQueueS(Squeue *, biTree *, int);
	bool isEmpty(Squeue *);
	bool deQueueS(Squeue *, biTree *, int);

	Stack *createStack(int);
	bool pushS(Stack *,biTree *);
	bool empty(Stack *);
	biTree *top(Stack *);
	bool pop(Stack *);

	s = createStack(maxSize);
	enQueueS(sq, p, maxSize);
	while (!isEmpty(sq)) {
		deQueueS(sq, r, maxSize);
		pushS(s,r);
		if (r->lchild)enQueueS(sq, r->lchild, maxSize);
		if (r->rchild)enQueueS(sq, r->rchild, maxSize);
	}
	while (!empty(s)) {
		r = top(s);
		printf("%c ",r->data);
		pop(s);
	}

}
int main() {
	int count = 0;
	struct biTree *T = (struct biTree *)malloc(sizeof(struct biTree));
	struct Squeue *sq = (struct Squeue *)malloc(sizeof(struct Squeue));

	biTree *create(biTree *);
	void nodeNum(biTree *, int *);

	Squeue *createQueue(int);
	T = create(T);//创建一颗二叉树
	nodeNum(T, &count);//统计二叉树节点个数
	sq = createQueue(count);

	levelOrder2(T, sq, count);
	return 0;
}

付出不在于多少,只要值得就好。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

北街学长

你的鼓励使我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值