(algorithm) The maximum distance of two nodes of a binary tree

Source: Internet
Author: User

Topic:

Find the farthest distance of the two nodes of the binary tree.

The binary tree is defined as follows:

Class Treenode{public:    int val;    Treenode* left;    treenode* right;    TreeNode (int x): Val (x), left (null), right (null) {}};
Ideas:

Traverse each node to find the longest path at the root of the current node, and then find the maximum value in all the longest paths.

Code:

Code Listing 1:

Class Node{public:    int val;    Node* left;    node* right;    int maxleft;    int maxright;}; void longestpath_1 (node* proot,int& maxlen) {    if (proot==null)        return;    if (proot->left==null)        proot->maxleft=0;    if (proot->right==null)        proot->maxright=0;    int Leftlen;    if (proot->left) {        longestpath_1 (proot->left,maxlen);        Leftlen=1+max (proot->left->maxleft,proot->left->maxright);        proot->maxleft=leftlen;    }    int Rightlen;    if (proot->right) {        longestpath_1 (proot->right,maxlen);        Rightlen=1+max (proot->right->maxleft,proot->right->maxright);        proot->maxright=rightlen;    }    Maxlen=max (Proot->maxleft+proot->maxright,maxlen);}

Code Listing 2:

Class Treenode{public:    int val;    Treenode* left;    treenode* right;    TreeNode (int x): Val (x), left (null), right (null) {}};void Longestpath (treenode* proot,int& maxleft,int& maxright,int& maxlen) {    if (proot==null) {        maxleft=0;        maxright=0;        maxlen=0;        return;    }    int maxleft_1,maxleft_2,maxright_1,maxright_2;    Longestpath (Proot->left,maxleft_1,maxright_1,maxlen);    Longestpath (Proot->right,maxleft_2,maxright_2,maxlen);    Maxleft=1+max (maxleft_1,maxright_1);    Maxright=1+max (maxleft_2,maxright_2);    Maxlen=max (Maxleft,maxright) +1;}

(algorithm) The maximum distance of two nodes of a binary tree

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.