实验名称

二叉树的应用

实验题目

建立一个由多种化妆品品牌价格组成的二叉树,并采用递归和非递归方法进行数据的遍历,按照遍历情况进行打印输出。具体功能包括:
(1)按照先序遍历创建一棵二叉树,各结点值为化妆品品牌价格;
(2)采用递归方法进行二叉树的前序、中序和后序遍历;
(3)采用非递归方法进行二叉树的前序、中序和后序遍历;

代码

#define _CRT_SECURE_NO_WARNINGS   
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#define MAXSIZE 30
typedef int datatype;
typedef struct node
{
datatype data;
struct node *lchild, *rchild;
}bintnode;
typedef bintnode *bintree;
bintree root;
typedef struct stack
{
bintree data[100];
int tag[100];
int top;
char name[20];
}seqstack;
void push(seqstack *s, bintree t) //进栈
{
s->data[s->top] = t; s->top++;
}
bintree pop(seqstack *s) //出栈
{
if (s->top != 0)
{
s->top--;
return (s->data[s->top]);
}
else return NULL;
}
bintree creatbintree() //创建
{
int ch;
scanf("%d", &ch);
bintree t;
if (ch == -1)
{
t = NULL;
}
else
{
t = (bintnode *)malloc(sizeof(bintnode));
t->data = ch;
t->lchild = creatbintree();
t->rchild = creatbintree();
}
return t;
}
/*===================递归遍历===================*/
void preorder(bintree t) //前序遍历递归算法
{
if (t)
{
printf("%d ", t->data);
preorder(t->lchild);
preorder(t->rchild);
}
}
void preorder1(bintree t)
{

}
void inorder(bintree t) //中序遍历
{
if (t)
{
inorder(t->lchild);
printf(" %d ",t->data);
inorder(t->rchild);
}
}
void postorder(bintree t) //后序遍历
{
if (t)
{
postorder(t->lchild);
postorder(t->rchild);
printf("%d ", t->data);
}
}
/*==================非递归遍历===================*/
void preorderl2(bintree t) //前序
{
seqstack s;
s.top = 0;
while ((t) || (s.top != 0))
{
if (t)
{
printf("%d ", t->data);
push(&s, t);
t = t->lchild;
}
else
{
t = pop(&s);
t = t->rchild;
}
}
}
void inorderl2(bintree t) //中序
{
seqstack s;
s.top = 0;
while ((t != NULL) || (s.top != 0))
{
if (t)
{
push(&s, t);
t = t->lchild;
}
else
{
t = pop(&s);
printf("%d ", t->data);
t = t->rchild;
}
}
}
void postoride2(bintree t)
{
seqstack s;
s.top = 0;
while ((t) || (s.top != 0))
{
if (t)
{
s.data[s.top - 1] = t;
s.tag[s.top] = 0;
s.top++;
t = t->lchild;
}
else
{
if (s.tag[s.top - 1] == 1)
{
s.top--;
t = s.data[s.top];
printf("%d ", t->data);
t = NULL;
}
else
{
t = s.data[s.top - 1];
s.tag[s.top - 1] = 1;
t = t->rchild;
}
}
}
}
int main()
{
printf("输入化妆品的品牌价格\n");
root = creatbintree();
printf("==========递归实现二叉树的遍历==========\n");
printf("前序遍历:输出化妆品的品牌价格\n");
preorder(root);
printf("\n");
printf("中序遍历:输出化妆品的品牌价格\n");
inorder(root);
printf("\n");
printf("后序遍历:输出化妆品的品牌价格\n");
postorder(root);
printf("\n");
printf("==========非递归实现二叉树的遍历==========\n");
printf("前序遍历:输出化妆品的品牌价格\n");
preorderl2(root);
printf("\n");
printf("中序遍历:输出化妆品的品牌价格\n");
inorderl2(root);
printf("\n");
printf("后序遍历:输出化妆品的品牌价格\n");
postoride2(root);
return 0;
// 19 10 3 -1 4 -1 -1 4 5 -1 -1 -1 5 -1 -1
}

运行截图:

建立一个由多种化妆品品牌价格组成的二叉树,并采用递归和非递归方法进行数据的遍历,按照遍历情况进行打印输出_二叉树递归和非递归遍历