数据结构——二叉树
来源:互联网 发布:c语言贪吃蛇源代码 编辑:程序博客网 时间:2024/05/20 22:41
二叉树前序,中序,后序,按层遍历:
#include <stdio.h>
#include <stdlib.h>
#include<iostream>
#include<queue>
using namespace std;
#define N 100
char *a="ABC##D#E##F##"; //扩充二叉树t的前序序列
typedef struct node//二叉树结构定义
{
char data;
struct node *lchild,*rchild;
}binnode;
typedef binnode *bintree;
//函数creatbintree (根据扩充二叉树的前序序列(字符串a)建立二叉树t的存储结构
bintree creatbintree()
{
char ch=*a++;
bintree t;
if (ch=='#') t=NULL;
else
{
t=(bintree)malloc(sizeof(binnode));
t->data=ch;
t->lchild=creatbintree();
t->rchild=creatbintree();
}
return t;
}
void preorder(bintree t) //前序递归遍历二叉树
{
if (t)
{
printf("%c",t->data);
preorder(t->lchild);
preorder(t->rchild);
}
}
void inorder(bintree t) //中序递归遍历二叉树
{
if (t)
{
inorder(t->lchild);
printf("%c",t->data);
inorder(t->rchild);
}
}
void postorder(bintree t)//后序递归遍历二叉树
{
if (t)
{
postorder(t->lchild);
postorder(t->rchild);
printf("%c",t->data);
}
}
void levelorder(bintree t) //按层遍历二叉树
{
queue<bintree>que;
que.push(t);
while(!que.empty())
{
bintree now=que.front();
que.pop();
cout<<now->data;
if(now->lchild)
{
que.push(now->lchild);
}
if(now->rchild)
{
que.push(now->rchild);
}
}
}
int main()
{
bintree t;
t=creatbintree(); //建立二叉树t的存储结构
printf("二叉树的前序序列为:\n");
preorder(t);
printf("\n");
printf("二叉树的中序序列为:\n");
inorder(t);
printf("\n");
printf("二叉树的后序序列为:\n");
postorder(t);
printf("\n");
printf("二叉树的按层遍历为:\n");
levelorder(t);
printf("\n");
return 0;
}
- 数据结构—二叉树
- 数据结构——二叉树
- 数据结构——二叉树
- 数据结构——二叉树
- 数据结构——二叉树
- 数据结构——二叉树
- 数据结构——二叉树
- 数据结构——二叉树
- 数据结构——二叉树
- 数据结构——二叉树
- 数据结构——二叉树
- 数据结构——二叉树
- 数据结构——二叉树
- 数据结构——二叉树
- 数据结构——二叉树
- 数据结构学习—二叉树
- 数据结构—平衡二叉树
- 数据结构—平衡二叉树
- print()和println()的区别
- 组装电脑步骤
- [一日一教学](27)退出CMD窗口:exit
- 文件上传与FormData对象的使用
- Crontab定时任务访问url实例
- 数据结构——二叉树
- mysql怎么完全卸载重装
- 并查集模板
- 递推的专题竞赛
- 关于eclipse中没有js代码提示的解决
- 优先队列模板
- Netty(二)TCP粘包、拆包和UDP通信
- 筛素数模板
- 处理输入成绩异常