Evaluate the tree diameter

Source: Internet
Author: User

For occasional questions, exercise the pointer by the way ..

# Include <iostream> using namespace STD; typedef struct node {int data; int child_num; node ** Childs;} * tree; /* calculate the height of 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 ;} /* calculate the diameter of 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 ");}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.