#include <iostream>using namespace std;//two fork tree node structure typedef struct TNODE_{INT data;struct tnode_*left;struct tnode_* Right;} tnode;//gets the height of the tree = Path +1 (the number of edges that the longest path passes through +1) int getlrdistance (tnode*t) {int len=0;if (t==null) {return 0;} Else{int lenl=getlrdistance (t->left); int lenr=getlrdistance (t->right); len= (LENL>LENR)? lenL:lenR;len+=1 ;//return (len+1);} return Len;} Gets the maximum distance between nodes in a tree (possibly two leaf nodes or leaf nodes with root nodes) int getmaxdistance (tnode*t) {int distance=0;if (t==null) {Distance=0;//return 0;} else if (t->left!=null && t->right==null) {//Determines whether the subtree is between two leaf nodes, or one of the leaf nodes and the root node int temp_distance= Getmaxdistance (t->left); int max_rootleft=getlrdistance (t->left); Distance=temp_distance>max_rootleft?temp_distance:max_rootleft;} else if (t->left==null && t->right!=null) {//Determines whether the subtree is between two leaf nodes, or one of the leaf nodes and the root node int temp_distance= Getmaxdistance (t->right); int max_rootleft=getlrdistance (t->right); Distance=temp_distance>max_rootleft?temp_distance:max_rootleft;} else if (t->Left!=null && t->right!=null) {//Determine if the left and right subtrees are between the height of the subtree + the height of the right subtree, or between the nodes of the Zuozi, or between the node of the subtree, int maxleft= Getmaxdistance (t->left); int maxright=getmaxdistance (t->right); int max_rootleft=0,max_rootright=0; Max_rootleft=getlrdistance (T->left); Max_rootright=getlrdistance (t->right); if (maxright<maxleft) distance=maxleft;else Distance=maxRight;int Temp =max_rootright+max_rootleft;if (temp>distance) distance=temp;} return distance;} void Outputf (tnode*t) {if (t!=null) cout<<t->data<< ""; else Return;outputf (T->left); OutputF (t-> right);} void Test () {tnode*t=new tnode ();t->data=1;t->left=t->right=null; Tnode*t1=new tnode ();t1->data=2;t1->left=t1->right=null; t->left=t1; Tnode*t2=new tnode ();t2->data=3;t2->left=t2->right=null;t1->left=t2; Tnode*t3=new tnode ();t3->data=4;t3->left=t3->right=null;t->right=t3; Tnode*t4=new tnode ();t4->data=5;t4->left=t4->right=null;t2->right=t4; Tnode*t5=new tnode (); T5->data=6;t5->left=t5->right=null;t3->right=t5; Tnode*t6=new tnode ();t6->data=7;t6->left=t6->right=null;t3->left=t6; Tnode*t7=new tnode (); t7->data=8;t7->left=t7->right=null;t6->left=t7;//printing the result of the first order traversal; OutputF (t);cout< <endl;cout<< maximum distance value for tree: <<getmaxdistance (t) <<endl;} int main () {Test (); return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Programming beauty finding the maximum distance between nodes in a binary tree