The beauty of programming: finding the maximum distance between nodes in a binary tree

Source: Internet
Author: User

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 ~

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.