read a few about the two fork tree node maximum distance of the article, feeling there are several better. Reprint, convenient to view, here to salute the original.
at the same time, there is a good, attached link Click to open the link
3.8 Finding the maximum distance of a node in a binary tree
is actually to find the diameter of the tree. Any two points of the tree must be in the left sub-tree part of a node and the right subtree part (assuming that the two subtree contains the node, so that the two adjacent points, the conclusion is also established). Therefore, the "diameter of the compute tree" is equivalent to "calculating the height and maximum of the Saozi right subtree for each node."
Many people will decompose the problem into "whether the path with the maximum distance between two points passes through the root node" two sub-problems, and then solve and judge these two sub-problems. In fact, these two points must be on a subtree with a node A as its root, and the path between them must pass through the root node A of that subtree. Thus, a subtree with any node as its root calculates the maximum distance through that subtree node, and the maximum distance is the maximum distance required. and the maximum distance through the root node of a tree = the height of the left subtree + the height of the right subtree +2 (assuming that the height of the empty node is-1), so you can use a global variable max_d to save the maximum distance, using depth-first traversal, each traversal of a node, calculate the height of the left and the subtree, calculate its height It compares the maximum distance value of the node with the Max_d value and updates the Max_d, and when all nodes are traversed, max_d is the maximum distance to be asked.
struct node{
Node *left;
Node *right;
Data
};
int Tree_height (node* root, int& max_d)
{
//each encounter a child node, the height is increased by 1, you can set the empty node height to 1,
//Avoid the judgment of empty nodes when calculating the height.
if (root==null) return-1;
int a = Tree_height (Root->left, max_d) + 1;
int b = Tree_height (Root->right, max_d) + 1;
int c = a+b;
if (Max_d < c) Max_d = C;
return a>b a:b;
}
int Tree_diameter (node* root)
{
int max_d=0;
Tree_height (Root, max_d);
return max_d;
}