c語言之循環隊列實現二叉樹的層次遍歷

二叉樹的層次遍歷思想就是從根結點開始,從左至右從上層往下層挨個遍歷。用一個數組實現的循環隊列來實現就比較簡單。根結點進入隊列,然後出隊,根節的左孩子不爲空的話左孩子進隊,後孩子不爲空的話右孩子進隊。然後循環如此直到循環隊列空爲止。
代碼如下:

#include<stdio.h>
#include<stdlib.h>
#define tree_size 6//定義二叉樹的結點爲6
typedef struct BinaryTree{//
    char data;//定義數據域
    struct BTNode *rChild;
    struct BTNode *lChild;
}BT;
BT* create_binary_tree(char data[]){//創建一顆結點數爲6的二叉樹
    BT *node[max];//定義指針數組來循環初始化二叉樹的結點
    for(int i=0;i<tree_size;i++){
        node[i] = (BT*)malloc(sizeof(BT));
        node[i]->data = data[i];
    }
    node[0]->lChild = node[1];//建立結點之間的關係       
    node[0]->rChild = node[2];
    node[1]->lChild = node[3];
    node[1]->rChild = node[4];
    node[2]->rChild = node[5];
    node[2]->lChild = NULL;//這步不能少哦,少了的話可能會出現異常
    node[3]->lChild = node[3]->rChild = NULL;
    node[4]->lChild = node[4]->rChild = NULL;
    node[5]->lChild = node[5]->rChild = NULL;
    return node[0];//返回根結點
}
void visit(BT  *p){//訪問結點函數
    if(p!=NULL){
        printf("%c\n",p->data);
    }
}
void levelTravel(BT *node){//隊列實現二叉樹的層次遍歷
    int rear,front;//定義循環隊列的頭尾位置
    BT  queue[tree_size];//循環隊列
    rear = front = 0;
    BT  *p = NULL;
    if(node==NULL){
        return;
    }
    rear = (rear+1)%tree_size;
    queue[rear] = node;//根結點入隊
    while(rear!=front){
       front = (front+1)%tree_size;
        p = queue[front];//根結點出隊
        visit(p);
        if(p->lChild!=NULL){
           rear = (rear+1)%tree_size;
            queue[rear] = p->lChild;//左孩子入隊
        }
        if (p->rChild!=NULL) {
           rear = (rear+1)%tree_size;
            queue[rear] = p->rChild;//右孩子入隊
        }
    }
}
int main(int argc, const char * argv[]) {
    char data[] = {'1','2','3','4','5','6'};//定義一個數組來給二叉樹的數據域賦值
    BT *root = (BT*)malloc(sizeof(BT));
    root = create_binary_tree(data);
    levelTravel(root);
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章