If we think of the two-fork tree as a graph, and the connection between the parent and child nodes is considered bidirectional, we'll define "example" as the number of edges between the two nodes. Write a program to find the distance between the two nodes farthest apart in a binary tree (the beauty of programming 3.8)
Idea: If two nodes are farthest apart, it must be two leaf nodes, or a leaf node to its root node.
According to the distance between the two nodes must be the leaf node of the law, we can further discuss.
For any one node, with that node as the root, assuming that the root Youk a child node, then the path between the two nodes at the farthest distance between U and V is in two cases with the root node.
1. If the path passes through root, then you and V belong to different subtrees, and they are the nodes farthest from the tree to the root node, otherwise they are contradictory to their furthest distance.
2. If the path does not go through root, then they must belong to one of the K subtrees of the root. And they are also the two vertices farthest apart from the subtree.
structNode {node*Pleft; Node*Pright; intmax_depth;//Maximum Depth intMax_distance;//Maximum Distance};structResult {intmax_depth; intmax_distance;};intMax (intAintb) {returna > B?a:b;} Result getmaxdistance (Node*proot) { if(Proot = =NULL) {Result Empty= {0, -1};//maximizes the initialization to 1 because the caller wants to add 1 to it and then 0 returnempty; } Result LHS= Getmaxdistance (proot->pleft); Result RHS= Getmaxdistance (proot->pright); result result; Result.max_depth= Max (lhs.max_depth +1, Rhs.max_depth +1); Result.max_distance= Max (max (lhs.max_distance, rhs.max_distance), lhs.max_depth + rhs.max_depth +2); returnresult;}
"Algorithm topic" Finding the maximum distance of a node in a binary tree