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

来源:互联网 发布:光纤分路器 什么网络 编辑:程序博客网 时间:2024/06/07 02:08

二叉树两种存储结构 顺序存储和链式存储 顺序

二叉树遍历分为 前序遍历 中序遍历 后序遍历 层次遍历

#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;}


阅读全文
0 0
原创粉丝点击