下列代码的功能是计算给定二叉树T的宽度。二叉树的宽度是指各层结点数的最大值。函数Queue_rear和Queue_front分别返回当前队列Q中队尾和队首元素的位置。
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 */
}
本文介绍了一种计算二叉树最大宽度的算法。通过使用队列存储每一层的节点,该算法能够遍历每一层并计算出各层节点数的最大值。核心步骤包括初始化队列、遍历节点、更新宽度等。
4927

被折叠的 条评论
为什么被折叠?



