层序遍历
规则是:若树为空,则空操作返回,否则从树的第一层,也就是根结点开始访问,从上而下逐层遍历,在同一层中,按从左到右的顺序对结点逐个访问。如图:
代码实现
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++]);
}
}
}