#include "OJ.h"
#include <string.h>
#include <stdio.h>
#include <queue>
using namespace std;
/*
Description
给定一个二叉树,获取该二叉树的宽度深度。
Prototype
int GetBiNodeInfo(BiNode &head, unsigned int *pulWidth, unsigned int *pulHeight)
Input Param
head 需要获取深度的二叉树头结点
Output Param
pulWidth 宽度
pulHeight 高度
Return Value
0 成功
1 失败或其他异常
*/
int g_tree_height;
void GetTreeHeight(BiNode *curNode,int curHeight)
{
if(NULL==curNode)
{
g_tree_height=curHeight>g_tree_height?curHeight:g_tree_height;
return;
}
curHeight++;
GetTreeHeight(curNode->left,curHeight);
GetTreeHeight(curNode->right,curHeight);
}
unsigned int GetTreeWidth(BiNode &head)
{
queue<BiNode> nodes[2];
int flag=0,result=-1;
nodes[flag].push(head);
while(!nodes[0].empty()||!nodes[1].empty())
{
int now=nodes[flag].size();
result=now>result?now:result;
while(!nodes[flag].empty())
{
BiNode CurNode=nodes[flag].front();
nodes[flag].pop();
if(NULL!=CurNode.left)
nodes[1-flag].push(*CurNode.left);
if(NULL!=CurNode.right)
nodes[1-flag].push(*CurNode.right);
}
flag=1-flag;
}
return result;
}
int GetBiNodeInfo(BiNode &head, unsigned int *pulWidth, unsigned int *pulHeight)
{
/*在这里实现功能*/
if(NULL==&head||NULL==pulHeight||NULL==pulWidth) return 1;
g_tree_height=0;
GetTreeHeight(&head,0);
*pulWidth=GetTreeWidth(head);
*pulHeight=g_tree_height;
return 0;
}
求二叉树的深度和广度
最新推荐文章于 2023-12-19 18:01:25 发布