各种结构的结构体一定要写对呀,差一个*都不行
马上要去上课了,贴完代码就先跑路了
树 {数据,左右孩子指针}
上下都有名字,还有一个带*的
队列 {数据,next指针}
上下都有名字
还有一个队头队尾指针,下面有名字栈{数据,top}
上下都有名字,一个总,一个分
#include<iostream>
using namespace std;
#define MAXSIZE 40
//树
typedef struct Treenode {
int data;
struct Treenode* lchild, * rchild;
}Treenode,*Tree;
//队列
typedef struct Linknode{
Treenode* data;//辅助队列保存指针
struct Linknode* next;
}Linknode;
typedef struct {
Linknode* front, * rear;
}Queue;
//栈
typedef struct Stacknode {
Treenode* data[MAXSIZE];
int top;
}LiStack;
//初始化树
void InitTree(Tree &T) {
T = NULL;
}
//建立有序二叉树
int bulid(Tree &T, int e) {
if (T == NULL) {//当前结点为空
T = new Treenode;
T->data = e;
T->lchild = NULL;
T->rchild = NULL;
return 0;
}
if (e < T->data) {//应插在左孩子
bulid(T->lchild, e);
}
else {
bulid(T->rchild, e);
}
return 0;
}
void visit(Tree T) {
cout << T->data << " ";
}
//先序遍历树
void preorder(Tree T) {
if (T != NULL) {
visit(T);
preorder(T->lchild);
preorder(T->rchild);
}
}
void midorder(Tree T) {
if (T!=NULL) {
midorder(T->lchild);
visit(T);
midorder(T->rchild);
}
}
//初始化队列
void InitQueue(Queue& Q) {
Q.front = Q.rear = NULL;
}
//入队
void enQueue(Queue& Q, Tree T) {
Linknode* p = new Linknode;
p->data = T;
p->next = NULL;
if (Q.front == NULL) {
Q.front = p;
Q.rear = p;
}
else {
Q.rear->next = p;
Q.rear = p;
}
}
//出队
bool deQueue(Queue& Q,Tree &p) {
if (Q.front == NULL) {
cout << "空队列" << endl;
return false;
}
else {
p = Q.front->data;
Q.front = Q.front->next;
if (Q.front == NULL)//最后一个结点
Q.rear = Q.front;
return true;
}
}
//判空队列
bool empty(Queue Q) {
if (Q.front == NULL)
return true;
return false;
}
//层次遍历
void wide_order(Tree T) {
Queue Q;
InitQueue(Q);
enQueue(Q, T);//根节点入队
Tree p;
while (!empty(Q)) {
deQueue(Q, p);//这里有问题
visit(p);
if (p->lchild != NULL) {
enQueue(Q, p->lchild);
}
if (p->rchild != NULL)
enQueue(Q, p->rchild);
}
}
//初始化栈
void InitStack(LiStack& S) {
S.top = -1;
}
//入栈
bool push(LiStack& S,Tree T) {
if (S.top == MAXSIZE - 1) {
return false;//满
}
else {
S.data[++S.top] = T;
return true;
}
}
//出栈
bool pop(LiStack& S, Tree& p) {
if (S.top == -1)
return false;
else {
p = S.data[S.top--];
return true;
}
}
//判空栈
bool emptyStack(LiStack S) {
if (S.top == -1)
return true;
return false;
}
//非递归中序遍历
void mid_order(Tree T) {
LiStack S;
InitStack(S);
Treenode* p = T;
while (p || !emptyStack(S)) {
if (p) {
push(S, p);
p = p->lchild;
}
else {
pop(S, p);
visit(p);
p = p->rchild;
}
}
}
int main() {
Tree T;
InitTree(T);
bulid(T, 10);
bulid(T, 20);
bulid(T, 8);
bulid(T, 22);
bulid(T, 5);
bulid(T, 9);
bulid(T, 7);
/*
树结构:
10
/ \
8 20
/ \ \
5 9 22
\
7
*/
cout << "先序遍历:";
preorder(T);
cout << endl;
//cout << Q.front->next->data->data;
/*Queue Q;
InitQueue(Q);
Tree p;
enQueue(Q, T);
enQueue(Q, T->lchild);
deQueue(Q, p);
cout << p->data;
deQueue(Q, p);
cout << p->data;*/
cout << "层次遍历:";
wide_order(T);
cout << endl;
cout << "递归中序遍历:";
midorder(T);
cout << endl;
cout << "非递归中序遍历:";
mid_order(T);
cout << endl;
return 0;
}