6-6 二叉樹的層次遍歷 (附完整代碼)(6 分)

本題要求實現給定的二叉樹的層次遍歷。

函數接口定義:

void Levelorder(BiTree T);`

T是二叉樹樹根指針,Levelorder函數輸出給定二叉樹的層次遍歷序列,格式爲一個空格跟着一個字符。
其中BinTree結構定義如下:

typedef char ElemType;
typedef struct BiTNode
{ ElemType data;
struct BiTNode *lchild, *rchild;
}BiTNode, *BiTree;

裁判測試程序樣例:

#include <stdio.h>
#include <stdlib.h>
typedef char ElemType;
typedef struct BiTNode
{
ElemType data;
struct BiTNode *lchild, *rchild;
}BiTNode, BiTree;
BiTree Create();/
細節在此不表 /
void Levelorder(BiTree T);
int main()
{
BiTree T = Create();
printf(“Levelorder:”); Levelorder(T); printf("\n");
return 0;
}
/
你的代碼將被嵌在這裏 */

輸出樣例(對於圖中給出的樹):

在這裏插入圖片描述

Levelorder: A B C D F G

代碼如下:


void Levelorder(BiTree T)
{
    BiTree q[1000];
    int front=0,rear =0;
    if(T)
    {
        q[rear++]=T;//根節點。
        while(front!=rear)
        {
            BiTree now=q[front++];
            printf(" %c",now->data);
            if(now->lchild) q[rear++]=now->lchild;
            //查找該層次左右子樹是否遍歷完成。
            if(now->rchild) q[rear++]=now->rchild;
        }

    }
}

完整代碼

測試數據
輸入:AB#DF##G##C##
輸出:ABDFGC
上面有圖
#include <stdio.h>
#include <stdlib.h>

typedef char ElemType;
typedef struct BiTNode
{
	ElemType data;
	struct BiTNode *lchild, *rchild;
}BiTNode, *BiTree;

BiTree Create();/* 細節在此不表 */

void Levelorder(BiTree T);

int main()
{
	BiTree T = Create();
	printf("Levelorder:"); Levelorder(T); printf("\n");
	return 0;
}
BiTree Create()
{
	char ch;
	scanf("%c", &ch);
	if (ch == '#')return NULL;
	BiTree T = (BiTree)malloc(sizeof(struct BiTNode));//struct可不寫。
		T->data = ch;
	T->lchild = Create();
	T->rchild = Create();
	return T;
}
void Levelorder(BiTree T)
{
	BiTree q[10050];
	int front = 0, rear = 0;
	if (T)//樹非空
	{
		q[rear++] = T;
		while (rear != front)
		{
			BiTree now = q[front]; front++;
			//數組中存放的是節點地址,用now接收,與鏈表相似
			printf(" %c", now->data);
			if (now->lchild)q[rear++] = now->lchild;//只能用now
			if (now->rchild)q[rear++] = now->rchild;
			//遞歸左右子樹,將下層中節點放入數組
		}
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章