先序遍历、中序遍历、后序遍历(递归),层次遍历
代码:
#include <iostream>
using namespace std;
#define MAXSIZE 10
//二叉树节点
typedef struct biNode{
char data;
biNode* lchild;
biNode* rchild;
}biNode, *biTree;
//队列,层次遍历时使用
class queue {
public:
//初始化
void InitQueue() {
data = new biNode*[MAXSIZE];
front = 0;
rear = 0;
}
//入队
bool EnQueue(biNode *node) {
if (IsFull()) {//判断队满
cout << "队满" << endl;
return false;
}
data[rear] = node;
rear = (rear + 1) % MAXSIZE;
return true;
}
//出队
biNode* DeQueue() {
//判断队空
if (IsEmpty()) {
cout << "队空" << endl;
return false;
}
biNode* temp;
temp = data[front];
front = (front + 1) % MAXSIZE;
return temp;
}
//返回当前数组长度
int Getlen() {
return (rear + MAXSIZE - front) % MAXSIZE;
}
//队空
bool IsEmpty() {
return (rear == front) ? true : false;
}
//队满
bool IsFull() {
return ((rear + 1) % MAXSIZE == front) ? true : false;
}
///输出队头元素
biNode* GetHead() {
if (!IsEmpty()) {
return data[front];
}
else {
return NULL;
}
}
//输出队列元素
void Output() {
cout << "队列长度:" << (rear + MAXSIZE - front) % MAXSIZE << endl;
if (Getlen() != 0) {
cout << "队列中的所有元素:";
int index = front;
while (index != rear) {
cout << data[index++] << ",";
}
cout << endl;
}
}
private:
biNode **data;
int front;
int rear;
};
//构造二叉树节点
void CreateBinode(biNode *n, char c) {
n->data = c;
n->lchild = NULL;
n->rchild = NULL;
}
//构造二叉树
void CreateBitree(biTree t) {
char ch[] = {'1','2','a','b','c','d'};
t->data = ch[0];
biNode *node1 = new biNode;
CreateBinode(node1, ch[1]);
t->lchild = node1;
biNode *node2 = new biNode;
CreateBinode(node2, ch[2]);
t->rchild = node2;
biNode *node3 = new biNode;
CreateBinode(node3, ch[3]);
t->lchild->lchild = node3;
biNode *node4 = new biNode;
CreateBinode(node4, ch[4]);
t->lchild->rchild = node4;
biNode *node5 = new biNode;
CreateBinode(node5, ch[5]);
t->lchild->rchild->lchild = node5;
}
//层次遍历
void LevelOrder(biTree t) {
queue q;
biNode* temp = NULL;
q.InitQueue();
q.EnQueue(t);
while (!q.IsEmpty()) {
temp = q.DeQueue();
cout << temp->data << ' ';
if (temp->lchild != NULL)
{
q.EnQueue(temp->lchild);
}
if (temp->rchild != NULL) {
q.EnQueue(temp->rchild);
}
}
}
//先序遍历
void PreOrder(biTree m) {
if (m!= NULL) {
cout << m->data << ' ';
PreOrder(m->lchild);
PreOrder(m->rchild);
}
}
//中序遍历
void InOrder(biTree t) {
if (t != NULL) {
InOrder(t->lchild);
cout << t->data << ' ';
InOrder(t->rchild);
}
}
//后序遍历
void PostOrder(biTree t) {
if (t != NULL) {
PostOrder(t->lchild);
PostOrder(t->rchild);
cout << t->data << ' ';
}
}
int main()
{
biTree bi = new biNode;
CreateBitree(bi);//构造一棵二叉树,其层次遍历为 1、2、a、b、c、d
cout << "先序遍历:";
PreOrder(bi);
cout << endl;
cout << "中序遍历:";
InOrder(bi);
cout << endl;
cout << "后序遍历:";
PostOrder(bi);
cout << endl;
cout << "层次遍历:";
LevelOrder(bi);
cout << endl;
}
控制台输出:
先序遍历:1 2 b c d a
中序遍历:b 2 d c 1 a
后序遍历:b d c 2 a 1
层次遍历:1 2 a b c d
注意事项:
创建树节点时(使用createNode()函数),如果在createNode()函数里面分配空间,需要将在堆上分配空间(定义指针,通过new分配空间),而不能在栈上分配空间(直接定义结构体),因为退出createNode()时,所有在栈上的内容都将失效;