Tree.h
#ifndef TREE_H
#define TREE_H 1
typedef int INT32;
typedef unsigned int UINT32;
typedef unsigned char UCHAR8;
typedef char CHAR8;
typedef long long int LONG64;
typedef unsigned long long int ULONG64;
typedef double DOUBLE64;
typedef float FLOAT32;
struct Node
{
INT32 data;
struct Node *left;
struct Node *right;
};
typedef struct Node *Pnode;
Pnode Create(); //创建二叉树
void LevelOrder(Pnode root); //层次遍历
#endif
Tree,cpp
#include<cstdio>
#include<queue>
#include<stdlib.h>
#include"tree.h"
using namespace std;
Pnode Create()
{
CHAR8 ch;
Pnode root;
scanf("%c",&ch);
if(ch == '@')
root = NULL;
else
{
root = (Pnode)malloc(sizeof(struct Node));
root->data = ch;
root->left = Create();
root->right = Create();
}
return root;
}
void LevelOrder(Pnode root) //优先队列实现二叉树层次遍历.
{
CHAR8 ch;
Pnode temp;
queue<Pnode> q;
if(root == NULL)
return ;
else
{
q.push(root);
while(!q.empty())
{
temp = q.front();
q.pop();
printf("%c ",temp->data);
if(temp->left != NULL)
q.push(temp->left);
if(temp->right != NULL)
q.push(temp->right);
}
}
}
main
#include<cstdio>
#include"tree.h"
int main()
{
Pnode root = Create();
LevelOrder(root);
printf("\n");
return 0;
}