16、层次遍历二叉树

题目:

输入一颗二元树,从上往下按层打印树的每个结点,同一层中按照从左往右的顺序打印。   例如输入

  8
  / \
 6 10
/ \ / \
5 7 9 11

输出8 6 10 5 7 9 11。


分析:

这一题就是考的二叉树的层次遍历。

代码如下:

#include <stdio.h>
#include <stdlib.h>
#include "TREE.h" //该头文件包含二叉树的建立和先序遍历

int front=0,rear=0;
BTNode * Queue[20];  
void Push(BTNode *s)
{
	Queue[rear++]=s;
}
void Pop()
{
	front++;
}

BTNode *GetTop()
{
	return Queue[front];
}

BTNode* Convert(BTNode *L);

int main()
{
	BTNode *L=NULL;
	CreateTree(&L);
	printf("The PreOrder Traversal of nodes in the tree are:  \n");
	OutputTree(L);
	printf("\n");
	printf("The LevelOrder Traversal of nodes in the tree are:  \n");
	L=Convert(L);
	printf("\n");

	return 0;
}

BTNode *Convert(BTNode *L)
{
	BTNode *temp,*cur;
	Push(L);
	while(front<rear)
	{
		cur=GetTop();//获取栈中首元素
		printf("%c  ",cur->num); //输出
		if (cur->lChild!=NULL)  //若有左节点,压入队列
		{
			Push(cur->lChild);
		}
		if (cur->rChild!=NULL)  //若有右结点,压入队列
		{
			Push(cur->rChild);
		}
		Pop();  //弹出首元素
	}
	return L;
}

TREE.H头文件:

#ifndef TREE_H
#define TREE_H

#include <stdio.h>
#include <stdlib.h>

typedef struct treeNode
{
	struct treeNode *lChild;
	struct treeNode *rChild;
	char num;
}BTNode;


void CreateTree(BTNode **L);//给出先序遍历,建立二叉树,无孩子结点用#代替。
                            //具体表述可参考http://acm.njupt.edu.cn/acmhome/problemdetail.do?&method=showdetail&id=1019
void OutputTree(BTNode *L); //先序遍历

void CreateTree(BTNode **L)  //注意这里传的是指针的地址!!!
{
	char ch;
	ch=getchar();
	getchar();
	if (ch=='#')
	{
		(*L)=NULL;
	}
	else
	{
		*L=(BTNode*)malloc(sizeof(BTNode));
		(*L)->num=ch;
		CreateTree(&((*L)->lChild));
		CreateTree(&((*L)->rChild));
	}
}

void OutputTree(BTNode *L)
{
	if (L)
	{
		printf("%c  ",L->num);
		OutputTree(L->lChild);
		OutputTree(L->rChild);
	}
}


#endif


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值