int treeWidth(TreeNode* root)
{
if (root==NULL)
{
return 0;
}
const int Max=1000;
TreeNode* array[Max];
int front=0,rear=0,num_p=rear;//num_p記錄該層最後一個結點的位置;
TreeNode* pNode=root;
array[rear]=pNode;
rear=rear+1;
num_p=rear;
int treeWidth=num_p-front;//記錄樹的寬度;
while(front<rear)
{
while(front<num_p)//當前層的結點出隊列,並將孩子加入隊列中;
{
pNode=array[front];
front=front+1;
if (pNode->left)
{
array[rear]=pNode->left;
rear=rear+1;
}
if (pNode->right)
{
array[rear]=pNode->right;
rear=rear+1;
}
}
num_p=rear;
if (treeWidth<(num_p-front))
{
treeWidth=(num_p-front);
}
}
return treeWidth;
}
樹的寬度
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.