There are two situations: either the depth of the tree (for example, the linked list), or the depth of the two Subtrees and the addition of 2. The final result is either the maximum distance from a subtree, or the depth and addition of 2 from the two subtree.
The specific procedure is as follows:
#include <stdio.h>template<typename T>class TreeNode { public: TreeNode() : left_(NULL), right_(NULL) { } TreeNode(const T& value) : value_(value), left_(NULL), right_(NULL) { } void LinkChild(TreeNode* left, TreeNode* right) { left_ = left; right_ = right; } T value_; TreeNode* left_; TreeNode* right_;};class VisitResult { public: VisitResult() {} VisitResult(int depth, int distance) : max_depth_(depth), max_distance_(distance) {} int max_depth_; int max_distance_;};template<typename T>T Max(const T& a, const T& b) { if (a >= b) { return a; } else { return b; }}template<typename T>VisitResult FindMaxDistance(TreeNode<T>* current) { if (current) { VisitResult left_result = FindMaxDistance(current->left_); VisitResult right_result = FindMaxDistance(current->right_); VisitResult res; res.max_depth_ = Max(left_result.max_depth_ + 1, right_result.max_depth_ + 1); res.max_distance_ = Max(Max(left_result.max_distance_, right_result.max_distance_), left_result.max_depth_ + right_result.max_depth_ + 2); return res; } else { VisitResult res(-1, 0); return res; }}int main(int argc, char** argv) { const int kNodeAmount = 7; TreeNode<int> tree[kNodeAmount]; for (int i = 0; i < kNodeAmount; ++i) { tree[i].value_ = i; } tree[0].LinkChild(tree + 1, NULL); tree[1].LinkChild(NULL, tree + 4); tree[4].LinkChild(tree + 5, tree + 6); tree[5].LinkChild(tree + 2, tree + 3); VisitResult res =FindMaxDistance(tree); printf("%d\n", res.max_distance_);}
References:
Programming beauty 3.8 p241
Http://www.cnblogs.com/miloyip/archive/2010/02/25/1673114.html