树的存储与遍历

本文介绍了一种使用C语言实现的二叉树结构,并通过递归方式实现了前序、中序和后序遍历。此外,还利用队列实现了层次遍历,展示了队列的基本操作如创建空队列、入队和出队等。

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

#include <stdio.h>
#include <stdlib.h>
#define N 10
typedef int datatype;
typedef struct _btnode_
{
 datatype no;
 struct _btnode_ *lchild, *rchild;
} bitree;
typedef struct
{
 bitree *data[N];
 int front, rear;
} sequeue;
sequeue *CreateEmptyQueue()
{
 sequeue *sq;
 sq = (sequeue *)malloc(sizeof(sequeue));
 sq->front = sq->rear = 0;
 return sq;
}
void EnQueue(sequeue *sq, bitree *r)
{
 sq->rear = (sq->rear + 1) % N;
 sq->data[sq->rear] = r;
 return;
}
bitree *DeQueue(sequeue *sq)
{
 sq->front = (sq->front + 1) % N;
 
 return sq->data[sq->front];
}
int EmptyQueue(sequeue *sq)
{
 return (sq->front == sq->rear);
}
bitree *CreateBitree(int i, int n)
{
 bitree *root;
 root = (bitree *)malloc(sizeof(bitree));
 root->no = i;
 if (2*i <= n)
 {
  root->lchild = CreateBitree(2*i, n);
 }
 else
 {
  root->lchild = NULL;
 }
 
 if ((2*i+1) <= n)
 {
  root->rchild = CreateBitree(2*i+1, n);
 }
 else
 {
  root->rchild = NULL;
 }
 return root;
}
void PreOrder(bitree *root)
{
 printf("%d ", root->no);
 if (root->lchild != NULL) PreOrder(root->lchild);
 if (root->rchild != NULL) PreOrder(root->rchild);
 return;
}
void InOrder(bitree *root)
{
 if (root->lchild != NULL) InOrder(root->lchild);
 printf("%d ", root->no);
 if (root->rchild != NULL) InOrder(root->rchild);
 return;
}
void PostOrder(bitree *root)
{
 if (root->lchild != NULL) PostOrder(root->lchild);
 if (root->rchild != NULL) PostOrder(root->rchild);
 printf("%d ", root->no);
 return;
}
void NoOrder(bitree *root)
{
 sequeue *sq;
 bitree *r;
 sq = CreateEmptyQueue();
 EnQueue(sq, root);
 while ( ! EmptyQueue(sq) )
 {
  r = DeQueue(sq);
  printf("%d ", r->no);
  if (r->lchild != NULL) EnQueue(sq, r->lchild);
  if (r->rchild != NULL) EnQueue(sq, r->rchild);
 }
 printf("\n");
}
int main()
{
 bitree *root;
 root = CreateBitree(1, 10);
 printf("PreOrder  : ");
 PreOrder(root);
 printf("\n");
 
 printf("InOrder   : ");
 InOrder(root);
 printf("\n");
 
 printf("PostOrder : ");
 PostOrder(root);
 printf("\n");
 printf("NoOrder   : ");
 NoOrder(root);
 return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值