Question: Given a binary tree, the distance between nodes is the number of nodes contained in the path between two nodes, and the maximum distance between nodes is obtained.
You can refer to the two articles: the beauty of programming: finding the maximum distance between nodes in a binary tree. Another solution and tree diameter
Ideas:
Find two information at each node: the height of the tree with the node as the root, and the maximum distance contained in the tree with the node as the root.
Because the maximum distance is obtained, if it is crossing the root node, the sum of the tree heights of the two Subtrees is + 1. If it is not crossing the root node, it is the maximum distance between left and right Subtrees.
Code:
① Refer to the first article and return two values each time:
1 struct treenode 2 {3 int val; 4 treenode * left, * right; 5}; 6 7 // each time two values 8 struct retval 9 {10 int height are returned; 11 int max_dist; 12 retval (int h, int D): height (H), max_dist (d) 13 {14} 15}; 16 17 retval maxdistintree (treenode * root) 18 {19 if (root = NULL) 20 return retval (0, 0); 21 22 retval LCR = maxdistintree (root-> left ); // left child result23 retval RCR = maxdistintree (root-> right); 24 25 retval result; 26 result. height = 1 + max (LCR. height, RCR. height); 27 result. max_dist = max (LCR. max_dist, RCR. max_dist), LCR. height + RCR. height + 1); 28 29 return result; 30}
② Refer to the second article to find the height and tree diameter respectively.
1 // separate height and diameter (maximum distance) 2 int treeheight (treenode * root) 3 {4 If (root = NULL) 5 {6 RETURN 0; 7} 8 else 9 {10 return 1 + max (treeheight (root-> left), treeheight (root-> right )); 11} 12} 13 14 int treediam (treenode * root) 15 {16 if (root = NULL) 17 return 0; 18 19 int l_height = treeheight (root-> left ); 20 int r_height = treeheight (root-> right); 21 22 int l_diam = treediam (root-> left); 23 int r_diam = treediam (root-> right ); 24 25 return max (l_diam, r_diam), 26 l_height + r_height + 1); 27}
Algorithm question -- the longest distance between nodes in a binary tree