If we look at the two-fork tree as a graph, and the connection between the parent and child nodes is two-way, let's define the number of edges between the two nodes as "distance". Write a program to find the distance between the two nodes farthest apart in a binary tree.
Solution: Using recursive method
1 //data structure Definition2 structNODE3 {4node* Pleft;//left dial hand tree5node* Pright;//Right sub-tree6 intNmaxleft;//The longest distance in the left dial hand tree7 intNmaxright;//The longest distance in the right sub-tree8 CharChvalue;//the value of the node9 };Ten One intNmaxlen =0; A - //find the longest two-segment distance in a tree - voidFindmaxlen (node*proot) the { - //traverse to leaf node, return - if(Proot = =NULL) - { + return; - } + A //If the left dial hand tree is empty, the maximum distance to the left of the node is 0 at if(Proot, Pleft = =NULL) - { -Proot-Nmaxleft =0; - } - - //If the right subtree is empty, the maximum distance to the right of the node is 0 in if(Proot, Pright = =NULL) - { toProot-Nmaxright =0; + } - the //If the left dial hand tree is not empty, recursively look for the longest distance of the left subtree * if(Proot-Pleft! =NULL) $ {Panax NotoginsengFindmaxlen (Proot,pleft); - } the + //If the right subtree is not empty, recursively look for the longest distance of the right subtree A if(Proot-Pright! =NULL) the { +Findmaxlen (Proot,pright); - } $ $ //Calculate Zuozi maximum node distance - if(Proot-Pleft! =NULL) - { the intNtempmax =0; - if(Proot, Pleft, Nmaxleft > Proot, Pleft,nmaxright)Wuyi { theNtempmax = Proot, pleftNmaxleft; - } Wu Else - { AboutNtempmax = Proot, pleftNmaxright; $ } -Proot-Nmaxleft = Ntempmax +1; - } - A //calculate the longest node distance of the right subtree + if(Proot-Pright! =NULL) the { - intNtempmax =0; $ if(Proot, Pright, Nmaxleft > Proot, Pright,nmaxright) the { theNtempmax = Proot, prightNmaxleft; the } the Else - { inNtempmax = Proot, prightNmaxright; the } theProot-Nmaxright = Ntempmax +1; About } the the //Update Maximum distance the if(Proot, Nmaxleft + proot, Nmaxright >Nmaxlen) + { -Nmaxlen = proot, Nmaxleft + prootNmaxright; the }Bayi}
The beauty of programming---Finding the maximum distance of a node in a binary tree