用层序遍历来实现,两个问题使用的方法相近;
void BinaryTreeWidth_level(TreeNode* root, int &width, int &height)
{
if(root == NULL)
{
height = 0;
width = 0;
return ;
}
TreeNode* p = root;
queue<TreeNode*> Q;
Q.push(p);
int maxwidth = 0;
int last_size = 1;
int level = 0;
while(!Q.empty())
{
last_size--;
if(last_size == 0)
{
maxwidth = Q.size() > maxwidth ? Q.size() : maxwidth ;
last_size = Q.size();
level++;
}
TreeNode* now = Q.front();
Q.pop();
if(now->lc != NULL)
Q.push(now->lc);
if(now->rc != NULL)
Q.push(now->rc);
}
height = level;
width = maxwidth;
return ;
}
|