C语言实现二叉树层次遍历


struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
};
struct    Queue {
    struct TreeNode *t;
    int rear;
    int front;
};

void InitQueue(struct Queue *q)
{
    q->t = malloc(sizeof(struct TreeNode) * M);
    q->rear = 0;
    q->front = 0;
    return;
}

int IsEmpty(struct Queue *q)
{
    if (q->front == q->rear)
        return 1;
    else
        return 0;
}
void EnQueue(struct Queue *q, struct TreeNode p)
{
    if ((q->rear + 1) % M == q->front)
        return;
    q->t[q->rear] = p;
    q->rear = (q->rear + 1) % M;
    return;
}

void DeQueue(struct Queue *q)
{
    if (q->rear == q->front)
        return;
    q->front = (q->front + 1) % M;
    return;
}
void preorder(struct TreeNode *root)
{
    if (!root)
        return;
    printf("%d ", root->val);
    preorder(root->left);
    preorder(root->right);
    return;

}


void Init(struct TreeNode *p, int val)
{
    p->left = NULL;
    p->right = NULL;
    p->val = val;
    return;
}


int main()
{
    struct TreeNode a;
    struct TreeNode b;
    struct TreeNode c;
    struct TreeNode d;
    struct TreeNode e;
    struct TreeNode f;
    struct TreeNode g;
    struct TreeNode h;
    struct TreeNode i;
    Init(&a, 1);
    Init(&b, 2);
    Init(&c, 5);
    Init(&d, 3);
    Init(&e, 4);
    Init(&f, 6);
    Init(&g, 8);
    Init(&h, 9);
    Init(&i, 10);
    a.left = &b;
    a.right = &c;
    b.left = &d;
    b.right = &e;
    c.left = NULL;
    c.right = &f;
    e.left = &h;
    e.right = &i;
    //preorder(&a);
    struct Queue Q;
    InitQueue(&Q);
    EnQueue(&Q,a);
    while (!IsEmpty(&Q))
    {
        printf("%d ", Q.t[Q.front].val);
        if(Q.t[Q.front].left)
            EnQueue(&Q,*Q.t[Q.front].left);
        if(Q.t[Q.front].right)
            EnQueue(&Q,*Q.t[Q.front].right);
        DeQueue(&Q);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/sinat_37372543/article/details/89395509