数据结构(五)层次遍历
// linear_listqueue.cpp : This file contains the 'main' function. Program execution begins and ends there.
//#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#define ElemType BiTree
using namespace std;
typedef struct BiTNode
{char data;struct BiTNode* lchild, * rchild;
}BitTNode, * BiTree;
typedef struct linknode //链式节点
{ElemType data;struct linknode* next;}LinkNode;//链式队列
typedef struct
{LinkNode* front, *rear;}LinkQueue;void InitQueue(LinkQueue &Q)
{//带头节点的队列初始化Q.rear=Q.front=(LinkNode*)malloc(sizeof(LinkNode));Q.front->next = NULL;
}bool IsEmpty(LinkQueue& Q)
{if (Q.rear == Q.front){return true;}return false;}void EnQueue(LinkQueue& Q, ElemType x)
{LinkNode* s= (LinkNode*)malloc(sizeof(LinkNode));s->data = x;s->next = Q.rear->next;Q.rear->next = s;Q.rear = s;}bool DeQueue(LinkQueue& Q, ElemType &x)
{if (IsEmpty(Q)){//队列为空return false;}LinkNode* p = Q.front->next;x = p->data;Q.front->next = p->next;if (p == Q.rear) //要删除的为尾队列{Q.rear = Q.front;}free(p);return true;
}//层次遍历
void LevelOrder(BiTree T)
{LinkQueue q;BiTNode* p;//初始化队列InitQueue(q);EnQueue(q,T); //将根节点入队while (!IsEmpty(q)){DeQueue(q,p);printf("%c\t",p->data);if (p->lchild != NULL){EnQueue(q,p->lchild);}if (p->rchild != NULL){EnQueue(q, p->rchild);}}}
bool createBiTree(BiTree& T)
{char ch;cin >> ch;if (ch == '.'){T = NULL; //如果输入 '.' , 该树空结点}else{T = (BitTNode*)malloc(sizeof(BitTNode));if (T == NULL){printf("tree error!\n");exit(1);}T->data = ch;createBiTree(T->lchild);createBiTree(T->rchild);}return true;
}int main()
{//int x;//LinkQueue Q;//InitQueue(Q);//EnQueue(Q, 5);//EnQueue(Q, 7);//EnQueue(Q, 9);//DeQueue(Q, x);//LinkNode* p = Q.front->next;//while (p != NULL)//{// printf("%d\n",p->data);// p = p->next;//}BiTree T;createBiTree(T);LevelOrder(T);}// Run program: Ctrl + F5 or Debug > Start Without Debugging menu
// Debug program: F5 or Debug > Start Debugging menu// Tips for Getting Started:
// 1. Use the Solution Explorer window to add/manage files
// 2. Use the Team Explorer window to connect to source control
// 3. Use the Output window to see build output and other messages
// 4. Use the Error List window to view errors
// 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
// 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
测试要完成如图