有两种情况,要么是树的深度(例如链表的情况),要么是两个子树的深度和加2。最终的结果要么来自某个子树的最大距离,要么来自两个子树的深度和加2。
具体程序如下:
#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_);
}
参考文献:
编程之美3.8 P241
http://www.cnblogs.com/miloyip/archive/2010/02/25/1673114.html