二叉樹的層次遍歷
層次遍歷,就是從上到下一層一層的遍歷 。其實主要就是要藉助一個隊列的先進先出,去遍歷
例如:spa
1code
2 3blog
4 5 6 7隊列
8 9 10 11 12 13 14 15it
代碼實現class
1 void BinaryTreeLevelOrder(BTNode* root) 2 { 3 Queue q; 4 //樹爲空,直接返回 5 if (root == NULL) 6 { 7 return; 8 } 9 QueueInit(&q); 10 //先將根節點入隊 11 QueuePush(&q, root); 12 while (QueueEmpty(&q)) 13 { 14 //出隊保存隊頭並訪問 15 BTNode* front = QueueFront(&q); 16 printf("%c", front->_data); 17 QueuePop(&q); 18 //將出隊結點的左子樹根入隊 19 if (front->_left) 20 QueuePush(&q, front->_left); 21 //將出隊結點的右子樹根入隊 22 if (front->_right) 23 QueuePush(&q, front->_right); 24 } 25 }