/*************************************************************************
> File Name: LongestDistance.cpp
> Author: Shaojie Kang
> Mail: kangshaojie@ict.ac.cn
> Created Time: 2015年09月12日 星期六 11时11分40秒
> Problem:
求一棵树中的最远距离
************************************************************************/
#include<iostream>
using namespace std;
struct TreeNode
{
TreeNode *left;
TreeNode *right;
};
struct Result
{
int maxDepth;
int maxDistance;
Result(){}
Result(int depth, int distance): maxDepth(depth), maxDistance(distance){}
};
Result GetLongestDistance(TreeNode *root)
{
if(!root)
return Result(-1, 0);
Result result;
Result leftResult = GetLongestDistance(root->left);
Result rightResult = GetLongestDistance(root->right);
result.maxDepth = max(leftResult.maxDepth, rightResult.maxDepth) + 1;
result.maxDistance = max(max(leftResult.maxDistance, rightResult.maxDistance), leftResult.maxDepth + rightResult.maxDepth + 2);
return result;
}
分析递归问题主要思路是:1. 先弄清楚递归的顺序。在递归的实现中,往往需要假设后续的调用已经完成,在此基础上,才实现递归的逻辑。在该题中,假设已经把后面的长度计算出来了,然后继续考虑后面的逻辑;2. 分析清楚递归体的逻辑,然后写出来。比如在上面的问题中,递归体的逻辑就是如何计算两边的距离。3. 考虑清楚递归退出的边界条件。也就是说,哪些地方应该写return.