注册 登录
编程论坛 数据结构与算法

【求助】帮我看看这段二叉树层次遍历代码哪里出错了

jingfeng_vae 发布于 2014-08-06 21:31, 654 次点击
#include<iostream>
#define MAX_Queue_SIZE 1000
using namespace std;
typedef struct  BiTNode
{
    char data;
    BiTNode *left_next,*right_next;
}BiTNode,*BiTree;
typedef struct Queue
{
   BiTNode *Data[MAX_Queue_SIZE];
   int front,rear;
}Queue;
void InitQueue(Queue &Q)
{
    Q.rear=Q.front=0;
}
bool EmptyQueue(Queue Q)
{
    if(Q.rear==Q.front)
        return true;
    else return false;
}
void EnterQueue(Queue &Q,BiTNode *p)//入队
{
    if((Q.rear+1)%MAX_Queue_SIZE==Q.front)
        return ;
    else
    {
        Q.Data[Q.rear]=p;
        Q.rear=(Q.rear+1)%MAX_Queue_SIZE;
    }
}
void DeQueue(Queue &Q,BiTNode *p)//出对
{
    if(Q.rear==Q.front)
         return ;
    else
    {
        p=Q.Data[Q.front];
        Q.front=(Q.front+1)%MAX_Queue_SIZE;
    }
}
void Create_Tree(BiTree &T)//建立二叉树
{
    char ch;
    cin>>ch;
    if(ch=='#')
        T=NULL;
    else
    {
        T=(BiTree)malloc(sizeof(BiTNode));
        T->data=ch;
        Create_Tree(T->left_next);
        Create_Tree(T->right_next);
    }
}
void Visit(char ch)
{
    cout<<ch<<" ";
}
void Level_Order_Tree(BiTree T,Queue &Q)//层次遍历
{
    BiTNode *p;
    p=T;
    EnterQueue(Q,p);
    while(!EmptyQueue(Q))
    {
        DeQueue(Q,p);
        Visit(p->data);
        if(p->left_next)
        {
            EnterQueue(Q,p->left_next);
        }
        if(p->right_next)
        {
            EnterQueue(Q,p->right_next);
        }
    }
}
int main()
{
    BiTree T;
    Create_Tree(T);
    Queue Q;
    InitQueue(Q);
    cout<<"层次遍历:";
    Level_Order_Tree(T,Q);
    cout<<endl;
    return 0;
}
0 回复
1