# 二叉树的查找(前序、中序、后序、层序遍历)--biaobiao88

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<malloc.h>
int MaxSize = 100;
using namespace std;
typedef char DataType;
typedef struct BiNode
{
DataType data;
struct BiNode *lchile,*rchild;
}BiNode;
BiNode *root;

//创建拓展二叉树，#代虚结点
BiNode *Creat(BiNode *root)//          cishu   /////
{
char ch;
cin >> ch;
if(ch == '#')
root = NULL;
else
{
root = (BiNode *)malloc(sizeof(BiNode));
root->data = ch;
root->lchile = Creat(root->lchile);
root->rchild = Creat(root->rchild);
}
return root;
}

//前序遍历
void PreOrder(BiNode *root)
{
if(root == NULL)
return;
else
{
cout << root->data << " ";
PreOrder(root->lchile);
PreOrder(root->rchild);
}
}

//中序遍历
void InOrder(BiNode *root)
{
if(root == NULL)
return;
else
{
InOrder(root->lchile);
cout << root->data << " ";
InOrder(root->rchild);
}
}

//后序遍历
void PostOrder(BiNode *root)
{
if(root == NULL)
return;
else
{
InOrder(root->lchile);
InOrder(root->rchild);
cout << root->data << " ";
}
}

//层序遍历
void LevelOrder(BiNode *root)
{
BiNode *q = NULL,*Q[MaxSize];
int front = -1;
int rear = -1;
if(root == NULL)
return;
Q[++rear] = root;
while(front != rear)
{
q = Q[++front];
cout << q->data << " ";
if(q->lchile != NULL)
Q[++rear] = q->lchile;
if(q->rchild != NULL)
Q[++rear] = q->rchild;
}

}

int main()
{
BiNode *root = NULL;
root = Creat(root);
cout << "该二叉树的根节点是：" << root->data << endl;
cout << endl;
cout << "该二叉树的前序遍历是：";
PreOrder(root);
cout << endl;
//    cout << "该二叉树的根节点是：" << root->data << endl;
cout << endl;
cout << "该二叉树的中序遍历是：";
InOrder(root);
cout << endl;
//    cout << "该二叉树的根节点是：" << root->data << endl;
cout << endl;
cout << "该二叉树的后序遍历是：";
PostOrder(root);
cout << endl;
//    cout << "该二叉树的根节点是：" << root->data << endl;
cout << endl;
cout << "该二叉树的层序遍历是：";
LevelOrder(root);
cout << endl;
return 0;
}

/*
abd##e##c#f##

*/

posted @ 2019-10-29 21:26  恶魔岛  阅读(...)  评论(...编辑  收藏