一步一步寫演算法(之二叉樹廣度遍曆)

來源:互聯網
上載者:User

【 聲明:著作權,歡迎轉載,請勿用於商業用途。  聯絡信箱:feixiaoxing @163.com】

    在二叉樹的遍曆當中,有一種遍曆方法是不常見的,那就是廣度遍曆。和其他三種遍曆方法不同,二叉樹的廣度遍曆需要額外的資料結構來協助一下?什麼資料結構呢?那就是隊列。因為隊列具有先進先出的特點,這個特點要求我們在遍曆新的一層資料之前,必須對上一次的資料全部遍曆結束。暫時還沒有掌握隊列知識的朋友可以看一看我的這一篇部落格—隊列。

    a)下面是新添加的隊列資料結構,其中資料部分換成了樹節點指標的指標:

typedef struct _QUEUE{int head;int tail;int length;TREE_NODE** pHead;}QUEUE;

    註:head表示開始,tail表示結束,length表示pHead的長度,pHead表示指標的起始地址

    b)建立隊列,因為涉及到length的長度問題,所以需要計算二叉樹中節點的總數

QUEUE* create_queue_for_tree(const TREE_NODE* pTreeNode){QUEUE* pQueue;int count;if(NULL == pTreeNode)return NULL;count = count_all_node_number(pTreeNode);pQueue = (QUEUE*)malloc(sizeof(QUEUE));assert(NULL != pQueue);memset(pQueue, 0, sizeof(QUEUE));pQueue->pHead = (TREE_NODE**)malloc(sizeof(TREE_NODE*)* count);assert(NULL != pQueue->pHead);memset(pQueue->pHead, 0, sizeof(TREE_NODE*) * count);pQueue->head = pQueue->tail = 0;pQueue->length = count;return pQueue;}

    c)實現隊列的資料加入和資料彈出操作

void insert_node_into_queue(QUEUE* pQueue, TREE_NODE* pNode){if(NULL == pQueue || NULL == pQueue->pHead ||NULL == pNode)return;pQueue->pHead[pQueue->tail ++] = pNode;return;}TREE_NODE* get_node_from_queue(QUEUE* pQueue){if(NULL == pQueue || NULL == pQueue->pHead)return NULL;if(pQueue->head == pQueue->tail)return NULL;return pQueue->pHead[pQueue->head++];}

    註:這裡定義的隊列不是迴圈隊列,所以資料的壓入和彈出比較簡單,直接對head和tail處理即可

    d)遍曆節點,按層得到資料,最後再pQueue->pHead中得到的指標資料就是按層輸出的結果

QUEUE* traverse_node_by_layer(TREE_NODE* pNode){QUEUE* pQueue;if(NULL ==pNode)return NULL;pQueue = create_queue_for_tree(pNode);assert(NULL != pQueue);/* 首個節點排入佇列 */insert_node_into_queue(pQueue, pNode);pNode = get_node_from_queue(pQueue);while(pNode){if(pNode->left)insert_node_into_queue(pQueue, pNode->left);if(pNode->right)insert_node_into_queue(pQueue, pNode->right);pNode = get_node_from_queue(pQueue);}return pQueue;}

擴充部分:

    上面的辦法已經可以實現隊列的按層輸出,那麼如果想在節點結構中直接實現資料的按層訪問怎麼辦?其實兩步走就可以:1)在已有的TREE_NODE添加prev和next;(2)按照剛才得到的pQueue->pHead結果,依次對prev和next進行賦值即可。不知道朋友們明白了沒?

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.