The beauty of programming 12: 3.8 calculates the maximum distance between nodes in a binary tree
Problem:
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 oneProgramCalculate the distance between the two nodes with the farthest distance in a binary tree.
In fact, it is to find the diameter of the tree.If the "Dynamic Planning Method" is adopted, the problem is divided into two subquestions: "Whether the path with the maximum distance between two points passes through the root node, then, judge the two subproblems. In fact, you don't have to worry about it.The two farthest points must be on the Child tree with a node A as the root, and the paths between them must pass through the root node A of the Child tree. Therefore, the maximum distance between the subtree that uses Node B as the root node is calculated, and the maximum distance between all the Subtrees is the maximum distance required for the binary tree, that is, "tree diameter ".The maximum distance of the root node passing through the tree is: the height of the Left subtree + the height of the right subtree + 2 (assuming that the height of the empty node is-1). Therefore,The original problem is equivalent to "calculating the height of the Left subtree and the right subtree of each node, taking the maximum value".
Struct Node {
Node*Left;
Node*Right;
IntData;
} ;
Static Int Tree_height (node * Root, Int & Max_distance)
{
// The height of each child node increases by 1. You can set the height of an empty node to-1,
// Avoid null node judgment when calculating the height.
If (Root = Null) Return - 1 ;
Int Left_height = Tree_height (Root -> Left, max_distance) + 1 ;
Int Right_height = Tree_height (Root -> Right, max_distance) + 1 ;
Int Distance = Left_height + Right_height;
If (Max_distance < Distance) max_distance = Distance;
Return Left_height > Right_height ? Left_height: right_height;
}
Int Tree_diameter (node * Root)
{
IntMax_distance= 0;
Tree_height (root, max_distance );
ReturnMax_distance;
}