層序遍歷
規則是:若樹為空,則空操作返回,否則從樹的第一層,也就是根結點開始訪問,從上而下逐層遍歷,在同一層中,按從左到右的順序對結點逐個訪問。如圖:
代碼實現
BiTree TreeQueue[1024];
int front = 0;
int rear = 0;
int LevelOrderTraverse(BiTree T) {
if (!isTreeExits) {
cout << "二叉樹不存在";
return -1;
}
if (!T&&isRoot==0) {
cout << "二叉樹為空,無元素";
}
if (T) {
isRoot++;
cout << T->data << " ";
if (T->lchild) {
TreeQueue[rear] = T->lchild;
rear++;
}
if (T->rchild) {
TreeQueue[rear] = T->rchild;
rear++;
}
if (front != rear) {
LevelOrderTraverse(TreeQueue[front++]);
}
}
}