顧名思義,就是一層一層的輸出內容。要實現這個功能,需要用到我們之前學到的佇列的相關操作。以二叉樹為例,,根節點先輸出,遍歷所有節點,把當前節點的左右子節點也加入佇列,若當前列隊不為空,則輸出隊頭節點,並獲取對頭節點的左右子節點加入佇列,直到隊列為空。
層序遍歷**
//層序遍歷
bool levelorder
(bitree tree)
return true;
}
測試**int
main
(int argc,
char
* ar**)
測試結果入隊1
出隊1入隊2
入隊3出隊2
入隊4入隊5
出隊3入隊6
出隊4入隊7
出隊5出隊6
出隊7
其他用到的**#include
"stdafx.h"
#include
"stdlib.h"
#include
"string.h"
#define maxsize 50
#define bool int
#define true 1
#define false 0;
typedef
struct binode
binode,
*bitree;
typedef
struct lnode
lnode;
typedef
struct
linkqueue;
void
initlinkqueue
(linkqueue *q)
bool islinkqueueempty
(linkqueue *q)
bool enlinkqueue
(linkqueue *q,binode *e)
binode*
delinkqueue
(linkqueue *q)
bool visit
(bitree tree)
void
inittree
(bitree &root)
C 樹的層序遍歷
層序遍歷的基本思路就是,1.根節點入佇列。2.根節點出隊,同時將根節點左兒子和右兒子入隊 3.結點出隊,同時將該節點的左兒子和右兒子入隊 4.重複3直到隊列為空 void layerprint struct treenode r include include fun.c struct queue ...
資料結構 二叉樹的層序遍歷
問題 給定乙個二叉樹,返回其按層次遍歷的節點值。即逐層地,從左到右訪問所有節點 例如 給定二叉樹 3,9,20,null,null,15,7 3 9 20 15 7 返回其層次遍歷結果 3 9,20 15,7 思路分析 這道題的要求是返回遍歷結果放在乙個二維陣列裡面,所以我們可以開闢三個陣列,第乙個...
資料結構實驗之二叉樹五 層序遍歷(c語言)
time limit 1000 ms memory limit 65536 kib problem description 已知乙個按先序輸入的字串行,如abd,eg,cf,其中,表示空結點 請建立二叉樹並求二叉樹的層次遍歷序列。input 輸入資料有多行,第一行是乙個整數t t 1000 代表有t...