Question: If we regard a binary tree as a graph and the line between parent and child nodes is bidirectional, we would like to define "distance" as the number of edges between two nodes. Write a program to find the distance between the two nodes with the farthest distance in a binary tree.
Analysis: the analysis on the tree is clear, There are two possible conditions for calculating the maximum distance of a binary tree:
1. The path goes through the deepest node of the Left subtree, and then to the deepest node of the right subtree through the root node.
2. The path does not pass through the root node, but is the maximum distance path of the Left or right subtree.
However, the Code on the tree uses additional node fields. Here is my code. The idea is the same:
Struct binarytree {int value; binarytree * left; binarytree * right; binarytree (int x): Value (x), left (null), right (null ){}}; void findmaxlength (binarytree * root, Int & depth, Int & maxlength) {If (root = NULL) {depth =-1; maxlength = 0; return;} int ldepth, rdepth, lmaxlength, rmaxlength; findmaxlength (root-> left, ldepth, lmaxlength); findmaxlength (root-> right, rdepth, rmaxlength); depth = max (ldepth, rdepth) + 1; maxlength = max (lmaxlength, rmaxlength); maxlength = max (maxlength, ldepth + rdepth + 2);} int findmaxlength (binarytree * root) {int depth, maxlength; findmaxlength (root, depth, maxlength); Return maxlength ;}