首页 > 学院 > 开发设计 > 正文

二叉树基本操作 遍历

2019-11-08 01:14:00
字体:
来源:转载
供稿:网友

建立一棵二叉树

struct BiTNode{    char data;    struct BiTNode *lchild, *rchild;};char t[51];int cnt;struct BiTNode *creatBiTree(){    struct BiTNode *T;    if(t[++cnt]==',')    {        T = NULL;    }    else    {        T = (struct BiTNode*)malloc(sizeof(struct BiTNode));        T->data = t[cnt];        T->lchild = creatBiTree();        T->rchild = creatBiTree();    }    return T;}void visit(struct BiTNode *T){    if(T->data!=',')     {        PRintf("%c", T->data);    }}

前序遍历void PreOrder(struct BiTNode *T){    if(T!=NULL)    {        visit(T);        PreOrder(T->lchild);        PreOrder(T->rchild);    }}

中序遍历void InOrder(struct BiTNode *T){    if(T!=NULL)    {        InOrder(T->lchild);        visit(T);        InOrder(T->rchild);    }}

后序遍历void PostOrder(struct BiTNode *T){    if(T!=NULL)    {        PostOrder(T->lchild);        PostOrder(T->rchild);        visit(T);    }}

层序遍历

void cengxu(struct BiTNode *T) {  int in = 0, out = 0;  struct node *a[1050];  a[in ++] = T;  while(in > out)  {    if (a[out] != NULL)     {       printf("%c",a[out] -> data);       a[in ++] = a[out] -> lchild;       a[in ++] = a[out] -> rchild;     }     out ++;  } }


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表