Calculate the maximum distance between a binary tree and the farthest node.

Source: Internet
Author: User
Perform the deformation of the binary tree height. The maximum distance is the height of the two Subtrees. (the height of an empty node is-1, and the height of the left and right Subtrees is 0)
The sum is + 2 or the max distance of the Left subtree or the maxdistance of the right subtree.
In actual processing, you only need to have one global variable, record the current maxdistance, and use post-order traversal. when accessing the root node, the large max distance in the left and right subtree has been recorded
In this global variable, if left depth + right depth + 2> max distance is updated
        int MaxDistance() {            int maxlen = 0;            find(this->m_root, maxlen);            return maxlen;        }        int find(T *root, int &maxlen) {            int ldepth, rdepth;            if (root->left())                ldepth = find(root->left(), maxlen);            else                ldepth = -1;            if (root->right())                rdepth = find(root->right(), maxlen);            else                rdepth = -1;            int depth;            if (ldepth > rdepth)                depth = ldepth + 1;            else                depth = rdepth + 1;            if ((ldepth + rdepth + 2) > maxlen)                maxlen = ldepth + rdepth + 2;            return depth;        }

Allen :~ /Study/data_structure/calculator $./test_max_diatance
1-1 2 3 4 5-1-1-1-1 6 7-1 8-1-1 9-1-1
1

2

3 6

4 7 9

5 8
The max distance is 6

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.