Seeing this question, I immediately thought of finding the depth of the binary tree (by finding the depth of the left and right Subtrees respectively, and then merging (taking the maximum value and adding 1) thus, the depth of the root node is obtained (in fact, the idea of sub-governance ))
The Code is as follows:
int Depth(Node *p)
{
int l_d , r_d;
if(p == NULL)
{
return 0;
}
l_d = Depth(p->lChild);
r_d = Depth(p->rChild);
return Max(l_d , r_d) + 1;
}
Now we need the maximum distance of A node. We can think about it in the same way: for A node, the maximum distance between the nodes in the subtree must be the depth of the Left subtree of A + the depth of the right subtree of A. Therefore, we only need to use the idea of "divide and conquer" to recursively solve the problem, and a MaxLen is used to maintain the maximum value:
int MaxLen = 0;
int FindMaxLen(Node *p)
{
int l_Len , r_Len;
if(p == NULL)
{
return 0;
}
l_Len = FindMaxLen(p->lChild);
r_Len = FindMaxLen(p->rChild);
MaxLen = Max(l_Len + r_Len , MaxLen);
return Max(l_Len , r_Len) + 1;
}
I personally feel much more concise than in the book ~