「递归逻辑实现」求一棵树中的最远距离
2015-09-12 11:23
375 查看
/*************************************************************************
> 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.
相关文章推荐
- 网页抽取技术和算法
- WWW-JavaScript
- mem系列函数(memset memcpy memmove) 和str系列函数(strlen strcpy strcmp strcat strstr strtok)
- StructLayout特性
- webbrowser 自动滚动网页
- Xcode添加空模板的路径
- 经纪xx系统节点VIP案例介绍和深入分析异常
- Android简易数据存储之SharedPreferences
- hdu 5291 dp+优化 ****
- MacBook常见的问题及解决方法
- python-04<关于字典:键必须是可哈希的>
- Nginx基础. Nginx通配散列表
- Nginx基础. Nginx基本哈希构成
- POJ 1423:Big Number 求N的阶乘的长度 斯特林公式
- Codeforces Gym 100548F Color (组合数+容斥)
- javascript仿天猫加入购物车动画效果
- POJ 1423:Big Number 求N的阶乘的长度 斯特林公式
- JavaScript获取onclick、onchange等事件值的代码
- 实用,为什么这样的一个数组?
- $PATH环境变量相关知识