程序填空题:二叉树的宽度
下列代码的功能是计算给定二叉树`T`的宽度。二叉树的宽度是指各层结点数的最大值。函数`Queue_rear`和`Queue_front`分别返回当前队列`Q`中队尾和队首元素的位置。
```c++
typedef struct TreeNode *BinTree;
struct TreeNode
{
int Key;
BinTree Left;
BinTree Right;
};
int Width( BinTree T )
{
BinTree p;
Queue Q;
int Last, temp_width, max_width;
temp_width = max_width = 0;
Q = CreateQueue(MaxElements);
Last = Queue_rear(Q);
if ( T == NULL) return 0;
else {
Enqueue(T, Q);
while (!IsEmpty(Q)) {
p = Front_Dequeue(Q);
@@[temp_width++](3);
if ( p->Left != NULL ) Enqueue(p->Left, Q);
@@[if ( p->Right != NULL ) Enqueue (p->Right, Q)](3);
if ( Queue_front(Q) > Last ) {
Last = Queue_rear(Q);
if ( temp_width > max_width ) max_width = temp_width;
@@[temp_width = 0](3);
} /* end-if */
} /* end-while */
return max_width;
} /* end-else */
}
```
答案:
第1空:temp_width++
第2空:if ( p->Right != NULL ) Enqueue (p->Right, Q)
第3空:temp_width = 0
```c++
typedef struct TreeNode *BinTree;
struct TreeNode
{
int Key;
BinTree Left;
BinTree Right;
};
int Width( BinTree T )
{
BinTree p;
Queue Q;
int Last, temp_width, max_width;
temp_width = max_width = 0;
Q = CreateQueue(MaxElements);
Last = Queue_rear(Q);
if ( T == NULL) return 0;
else {
Enqueue(T, Q);
while (!IsEmpty(Q)) {
p = Front_Dequeue(Q);
@@[temp_width++](3);
if ( p->Left != NULL ) Enqueue(p->Left, Q);
@@[if ( p->Right != NULL ) Enqueue (p->Right, Q)](3);
if ( Queue_front(Q) > Last ) {
Last = Queue_rear(Q);
if ( temp_width > max_width ) max_width = temp_width;
@@[temp_width = 0](3);
} /* end-if */
} /* end-while */
return max_width;
} /* end-else */
}
```
答案:
第1空:temp_width++
第2空:if ( p->Right != NULL ) Enqueue (p->Right, Q)
第3空:temp_width = 0