题目:http://www.wikioi.com/problem/1501/
给你一颗二叉树,求该数的宽和高,
首先求出树的高,直接进行二叉树遍历,能够得到二叉树的高
然后是得到宽,本人采用的是一层一层的遍历,求出每一层节点的个数,最大的则是该树的宽了,
代码:
#include <cstdio>
#include <cstring>
#include <stack>
#include <queue>
#include <iostream> using namespace std; #define L 1
#define R 2
class tree{
private:
int a[][],h,w;
stack<int> mystack;
public:
tree();
void set_tree(int i,int x,int y);
void tree_h(int i,int t);//得到高
void BFS(int t);//得到宽
int get_h();
int get_w();
}; tree::tree()
{
memset(a,,sizeof(a));
h = ;
w = ;
} void tree::set_tree(int i,int x,int y)
{
a[i][L] = x;
a[i][R] = y;
}
int tree::get_h()
{
int t = ;
tree::tree_h(a[][L],t+);
tree::tree_h(a[][R],t+);
return h-;
}
int tree::get_w()
{
mystack.push();
tree::BFS();
return w;
}
void tree::BFS(int i)
{
if(i <= h)
{
int t = ,x;
stack<int> tmpstack;
while(mystack.empty() == false)
{
x = mystack.top();
mystack.pop();
if(x != )
{
t++;
tmpstack.push(a[x][L]);
tmpstack.push(a[x][R]);
}
} w = w > t ? w : t;
mystack = tmpstack;
tree::BFS(i+);
}
} void tree::tree_h(int i,int t)
{
if(i == )
{
h = h > t ? h : t;
return;
}
else
{
tree::tree_h(a[i][L],t+);
tree::tree_h(a[i][R],t+);
}
}
int main()
{
int n,x,y;
while(~scanf("%d",&n))
{
tree mytree;
for(int i = ; i <= n; i++)
{
scanf("%d%d",&x,&y);
mytree.set_tree(i,x,y);
}
int h = mytree.get_h();
int w = mytree.get_w();
printf("%d %d\n",w,h);
}
return ;
}