宽度优先(层次)遍历二叉树
记录一下步骤:
- 将根结点入队;
- 队首出队并打印;
- 将队首的孩子入队,先左再右;
- 重复2、3.
void breadthFirst(BT* root) {
if (root == NULL)
return;
queue<BT*> bfs;
bfs.push(root);
while (!bfs.empty()) {
root = bfs.front();
bfs.pop();
cout << "Node " << root->num
<< " 's text is " << root->text << endl;
if (root->lchild != NULL)
bfs.push(root->lchild);
if (root->rchild != NULL)
bfs.push(root->rchild);
}
}
求一棵二叉树的最大宽度
这里二叉树的宽度指的是二叉树某一层上的结点数量,最大宽度就是结点数量最多的那一层的结点数量(有点绕哈哈)。
记录一下这个算法的主要步骤:
- 申请一个结点curEnd用于记录当前层的最后一个结点,初始化为根结点;
- 申请一个nextEnd用于记录下一层的最后一个结点;
- 申请一个max用于记录最大宽度,cur用于记录当前宽度;
- 将根结点入队;
- 队首出队并使当前层宽度+1(++cur);
- 使出队结点的左右孩子入队,先左再右,每次将新结点入队时都使nextEnd指向新入队的结点;
- 重复5、6;
- 当出队结点到达当前层的末尾时(root == curEnd),令curEnd = nextEnd以开始下一层的遍历,并比较max和cur,将较大值赋给max,最后将cur置0,开始记录下一层宽度;
- 最后返回max.
int max_breadth(BT* root) {
BT* curEnd{ root }, * nextEnd{ NULL };
int max{ 0 }, cur{ 0 };
queue<BT*> mb;
mb.push(root);
while (!mb.empty()){
root = mb.front();
mb.pop();
++cur;
if (root->lchild != NULL) {
mb.push(root->lchild);
nextEnd = root->lchild;
}
if (root->rchild != NULL) {
mb.push(root->rchild);
nextEnd = root->rchild;
}
if (root == curEnd) {
curEnd = nextEnd;
max = cur > max ? cur : max;
cur = 0;
}
}
return max;
}