二叉树的层次遍历

#include <stdio.h>
#include <stdlib.h>
#include "tree.h"
#include "lk.h"
/*typedef struct tree{
        int data;
        struct tree *lchild;
        struct tree *rchild;
}TREE;
*/
TREE *create1(int i,int n )
{
    TREE *root=(TREE *)malloc(sizeof(TREE));
    if(root==NULL)
        return NULL;
    root->data=i;
    if(2*i<=n)
    {
    root->lchild=create1(2*i,n);
    }
    else 
    root->lchild= NULL;

    if(2*i+1<=n)
    {
    root->rchild=create1(2*i+1,n);
    }
    else 
    root->rchild= NULL;

    return root;

}
void xian(TREE *root)

{
    if(root==NULL)
        return  ;
    printf("%d ",root->data);
    xian(root->lchild);
    xian(root->rchild);
}
void zhong(TREE *root)
{
    if(root==NULL)
        return  ;
    zhong(root->lchild);
    printf("%d ",root->data);
    zhong(root->rchild);
}
void hou(TREE *root)
{
    if(root==NULL)
        return  ;
    hou(root->lchild);
    hou(root->rchild);
    printf("%d ",root->data);
}
//cengci

void fcengci(TREE *root)
{
    if(NULL==root)
        return ;
    LIST *list=create();
    insert(list,root);
    while(empty(list)!=1)
    {
       TREE *root=del(list);
       printf("%d ",root->data);
       if(root->lchild!=NULL)
       {
        insert(list,root->lchild);
       }
       if(root->rchild!=NULL)
       {
        insert(list,root->rchild);
       }
    }

    return ;
}
int main(int argc, char *argv[])
{ 
    TREE *p=create1(1,12);
    printf("xian:");
    xian(p);
    putchar('\n');
    printf("zhong:");
    zhong(p);
    putchar('\n');
    printf("hou:");
    hou(p);
    putchar('\n');
    fcengci(p);

    putchar('\n');
    
    return 0;
} 

lk.h里面是链队的操作

#ifndef lkl
#define lkl
#include "tree.h"
typedef TREE *data_t;
typedef struct node{
    data_t data;                                                 
     struct node *next;                                          
  }NODE;//tou jie dian                                          
  typedef struct list{
      struct node *front;                                    
      struct node *rear;
  }LIST;
LIST *create();
int empty(LIST *list);
int lenth(LIST *list);
int insert(LIST *list,data_t data);
data_t  del(LIST *list);
void dayin(LIST *list);
#endif

tree.h如下

#ifndef  tree_
#define  tree_
typedef struct tree{
          int data;
          struct tree *lchild;
         struct tree *rchild;
 }TREE;
TREE *create1(int i,int n);
void xian(TREE *root);
void zhong(TREE *root);
#endif

链队的操作就不放了

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值