二叉树必学算法(三):二叉树的层序遍历

二叉树的层序遍历


/**
 * title: 二叉树的层序遍历
 * author: Whywait
 */

void LevelOrder(BiTree T) {
     
    InitQueue(Q);                       //initialize a Queue named Q
    BiTree p;                           //the traversing pointer
    EnQueue(Q, T);                      //enqueue the root node
    while (!isEmpty(Q)) {
                    //while the Q is not empty
        DeQueue(Q, p);                  //dequeue the first the node in the queue and name it p
        visit(p);                       //visit p
        if (p->lchild != null)
            EnQueue(Q, p->lchild);      //enqueue the left child of p
        if (p->rchild != NULL)
            EnQueue(Q, p->rchild);      //enqueue the right child of p
    }
}

/**
 * Tips:
 *  use BFS, please remember the codes front as model.
 *  Because the use of the BFS, a Queue is always needed in such an algorithm.
 */

你可能感兴趣的:(算法,二叉树,算法,面试,层序遍历)