您的位置:首页 > 理论基础 > 数据结构算法

暑假集训 二叉树 大话数据结构上讲的

2017-07-13 17:30 399 查看
二叉树两种存储结构 顺序存储和链式存储 顺序

二叉树遍历分为 前序遍历 中序遍历 后序遍历 层次遍历 #include <iostream>
#include <stdlib.h>
#include<string>
#include<cstdio>
using namespace std;
typedef struct bitnode
{
struct bitnode* leftchild; // 指针 注意 typedef 创建一个指针
struct bitnode* rightchild;
char data;
}bitnode,*bitree;
void creattree(bitree &t) // 用递归建立二叉树 输入#为没有数据
{
char ch;
cin>>ch;
if(ch=='#')
t=NULL;
else
{
t=(bitnode *)malloc(sizeof(bitnode));
t->data=ch; //
t->leftchild=new bitnode;
t->rightchild=new bitnode;
creattree((t)->leftchild);
creattree((t)->rightchild);
}
}
void preorder(bitree t)
{
if((t)!=NULL)
{
cout<<(char)t->data;
if(t->leftchild!=NULL)
{
preorder(t->leftchild);
}
if(t->rightchild!=NULL)
{
preorder(t->rightchild);
}
}
}
void dowork()
{
bitnode* cam;
creattree(cam);
preorder(cam);
}
int main()
{
dowork();
return 0;
}中序和后序就把先序的位置换一下就OK了
这是先序的代码

void preorder(bitree t) //先序
{
if((t)!=NULL)
{
cout<<(char)t->data;
if(t->leftchild!=NULL)
{
preorder(t->leftchild);
}
if(t->rightchild!=NULL)
{
preorder(t->rightchild);
}
}
}中序
void inode(bitree t)
{
if(t!=NULL)
{
inode(t->leftchild);
cout<<t->data;
inode(t->rightchild);
}
}后序
void prostnode(bitree t)
{
if(t!=NULL)
{
prostnode(t->leftchild);
prostnode(t->rightchild);
cout<<t->data;
}
}主函数调用
int main()
{
bitnode* cam;
creattree(cam);
preorder(cam);
cout<<endl;
inode(cam);
cout<<endl;
prostnode(cam);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: