二叉树层次遍历

原理:层次遍历与队列的的先进先出是类似,所以借助队列去做

例如:给定一颗这样的二叉树

代码

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include <stdlib.h>

typedef struct bitree {
	char data;
	struct bitree* lchild, * rchild;
}bitree;

typedef struct {
	bitree *data[50];
	int front, rear;
}sequeue;//队列
	
//创建二叉树
bitree* create(bitree* t) {
	char ch;
	scanf("%c", &ch);
	if (ch == '#') {
		return NULL;
	}
	else {
		t = (bitree*)malloc(sizeof(bitree));
		t->data = ch;
		t->lchild = create(t->lchild);
		t->rchild = create(t->rchild);
		return t;
	}
}

//层次遍历
void levelorder(bitree* t) {
	sequeue s;
	s.front = s.rear = 0; //队列初始化
	bitree *p = t;
	s.data[(s.rear)++] = t; //根结点入队
	while (s.front!=s.rear) {
		p = s.data[(s.front)++];
		printf("%c", p->data);
		if (p->lchild != NULL) {  //入队
			s.data[(s.rear)++] = p->lchild; 
		}
		if (p->rchild != NULL) { //入队
			s.data[(s.rear)++] = p->rchild;
		}
	}
}

int main() {
	bitree* t = NULL;
	t = create(t);
	levelorder(t);
}

相关推荐

  1. 层次

    2024-01-02 20:08:01       19 阅读
  2. Leetcode 107:层次II

    2024-01-02 20:08:01       9 阅读
  3. Leetcode 102:层次

    2024-01-02 20:08:01       10 阅读
  4. leetcode-11-前中后序以及层次

    2024-01-02 20:08:01       6 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-02 20:08:01       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-02 20:08:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-02 20:08:01       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-02 20:08:01       20 阅读

热门阅读

  1. skynet 配置中lua服务创建流程

    2024-01-02 20:08:01       28 阅读
  2. MySQL 8.0 ReplicaSet备库切换为可读写单库

    2024-01-02 20:08:01       33 阅读
  3. 头歌:旅游网站大数据分析 - 数据抓取

    2024-01-02 20:08:01       46 阅读
  4. 前端需要学GraphQL 吗?

    2024-01-02 20:08:01       41 阅读
  5. C++精进之路(十二)类和动态内存分配

    2024-01-02 20:08:01       32 阅读
  6. 91 两个数组的交集II

    2024-01-02 20:08:01       37 阅读
  7. 用g2o实现bundle adjustment

    2024-01-02 20:08:01       41 阅读
  8. 94. 二叉树的中序遍历(“颜色标记法”)

    2024-01-02 20:08:01       29 阅读