求樹的直徑

來源:互聯網
上載者:User

偶爾看到的題目,順便練習下指標。。

#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");}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.