偶尔看到的题目,顺便练习下指针。。
#include <iostream>
using namespace std;
typedef struct node {
int data;
int child_num;
node **childs;
}*tree;
/*求tree t的高度*/
int Height(tree t){
int h = 0;
for(int i=0;i<t->child_num;i++){
h = max(h,Height(t->childs[i]) );
}
return h + 1;
}
/* 求tree t的直径*/
int Diameter(tree t){
int _max1=0,_max2=0,tmp,_max;
for(int i=0;i<t->child_num; i++){
tmp = Height(t->childs[i]);
if(tmp > _max1) _max2 = _max1, _max1 = tmp;
else if(tmp > _max2) _max2 = tmp;
}
_max = _max1 + _max2 + 1;
for(int i=0;i<t->child_num; i ++) {
_max = max(Diameter(t->childs[i]),_max);
}
return _max;
}
int main(){
tree t5 = new node();
tree t4 = new node();
tree t3 = new node();
t3->child_num = 1;
t3->childs = new tree;
t3->childs[0] = t5;
tree t2 = new node();
t2->child_num = 1;
t2->childs = new tree;
t2->childs[0] = t4;
tree t1 = new node();
t1->child_num = 2;
t1->childs = new tree[2];
t1->childs[0] = t2;
t1->childs[1] = t3;
tree t6 = new node();
t6->child_num = 1;
t6->childs = new tree;
t6->childs[0] = new node();
tree t = new node();
t->child_num = 2;
t->childs = new tree[2];
t->childs[0] = t1;
t->childs[1] = t6;
cout<<Diameter(t)<<endl;
system("pause");
}