C 语言创建二叉树并进行层次遍历的程序示例(无需修改,直接运行)

#include<iostream>
#include<stdlib.h>

typedef struct TB {
	struct TB* lchild;
	struct TB* rchild;
	int data;
} BTnode,*BTree;
BTree Create(BTree &T) {
	int c;
	BTree p,q;

	scanf("%d",&c);
	if(c==0) {
		return NULL;
	} else {
		T=(BTree)malloc(sizeof(BTnode));
		T->data=c;
		T->lchild=Create(T->lchild);
		T->rchild=Create(T->rchild);
		return T;
	}

}
void Cenci1(BTree T) {

	printf("二叉树层次遍历开始\n");
	BTree p=T,q,s[99];
	int front=0,last=1,level=0,index=0;
	s[front]=p;
	while(front<last) {
		while(front<=index) {
			p=s[front++];
			printf("%d",p->data);
			if(p->lchild)s[last++]=p->lchild;
			if(p->rchild)s[last++]=p->rchild;

		}
		printf("\n");
		index=last-1;
		level++;
	}
}

int main() {
	BTree T;
	printf("二叉树创建开始\n");

	Cenci1(Create(T));


}

程序中创建二叉树时依据先序遍历的方式。用户首先开始输入数据,当输入 0 时表示当前节点为空,停止创建。若输入非 0 值,则先为当前节点分配内存空间,将输入值赋给该节点的数据域。接着按照先序遍历的顺序,先递归创建左子树,再递归创建右子树。这种先序输入创建的方式符合先序遍历的访问顺序,即先访问根节点,再访问左子树,最后访问右子树,以此来构建完整的二叉树结构。层次遍历部分则利用队列依次访问每一层的节点并输出。 

 

  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值