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