二叉树层序遍历

#include<stdio.h>
#include<stdlib.h>
#define NULL 0
#define MAXSIZE 100
typedef struct BTNode
{
    struct BTNode *lchild,*rchild;
    int data;
}BTNode,*btnode;

void createBtree(btnode &T)
{
    int t;
    scanf("%d",&t);
    if(t==0)
        T=NULL;
    else
    {
        T=(btnode)malloc(sizeof(BTNode));
        T->data=t;
        createBtree(T->lchild);
        createBtree(T->rchild);
    }
}

void level(btnode &p)
{
    int front,rear;
    btnode que[MAXSIZE];
    btnode q;
    front=rear=0;
    if(p!=NULL)
    {
        rear=(rear+1)%MAXSIZE;
        que[rear]=p;
        while(front!=rear)
        {
            front=(front+1)%MAXSIZE;
            q=que[front];
            printf("%d ",q->data);
            if(q->lchild)
            {
                rear=(rear+1)%MAXSIZE;
                que[rear]=q->lchild;
            }
            if(q->rchild)
            {
                rear=(rear+1)%MAXSIZE;
                que[rear]=q->rchild;
            }
        }
    }
}


void main()
{
    btnode T;
    createBtree(T);
    printf("level trave:");
    level(T);
    printf("\n");
}


你可能感兴趣的:(二叉树)