#include<iostream>
#include<queue>
using namespace std;
typedef int T;
struct treeNode
{
T data;
struct treeNode *left, *right;
treeNode(T d, treeNode *l=NULL, treeNode *r=NULL):data(d),left(l),right(r) {};
};
int width(const treeNode * root)
{
if(root == NULL) return 0;
int Width = 1;
int LastLevelWidth = 0;
int TempLastLevelWidth = 0;
int CurLevelWidth = 0;
queue<treeNode *> myQueue;
treeNode *tree = new treeNode(0,root->left,root->right);
myQueue.push(tree);
LastLevelWidth = 1;
treeNode *Cur = NULL;
while(!myQueue.empty())
{
TempLastLevelWidth = LastLevelWidth;
while(TempLastLevelWidth != 0 )
{
Cur = myQueue.front();
myQueue.pop();
if(Cur->left) myQueue.push(Cur->left);
if(Cur->right) myQueue.push(Cur->right);
TempLastLevelWidth--;
}
CurLevelWidth = myQueue.size();
Width = CurLevelWidth > Width ? CurLevelWidth : Width;
LastLevelWidth = CurLevelWidth;
}
return Width;
}
二叉树的宽度C++
最新推荐文章于 2024-09-29 14:05:03 发布