本文共 1711 字,大约阅读时间需要 5 分钟。
一:递归获得二叉树高度
因为树本身就是递归定义,创建也可以递归创建,所以高度不也可以递归获得嘛?如下:
int getHeight(Node* pNode){ if (pNode) { 左树高度 = getHeight(pNode->lChild) 右树高度 = getHeight(pNode->rChild) return 左右树高度较大者 + 1 } else { return 0; }}
关于树的问题很多都和递归思想有关。
二:递归得出所有可能
华为OJ上一道题:http://career-oj.huawei.com/exam/ShowSolution?method=SolutionApp&id=2091;
这种题目显然是必须弄出所有可能情况,而且用循环的方式不好做,并且每一层处理都是类似的,很容易想到递归的思想。
#include #include #include #include #include #include #include using namespace std;#define DEBUGset s; //装不同结果的集合void handleRes(const int& n, const int* pWeight, const int* pNum, int* pCalc, const int thisIndex){ //对这种重量的砝码,取不同的个数 for (int i = 0; i <= pNum[thisIndex]; i++) //注意:这里可以等于!!! { //先取 pCalc[thisIndex] = i; //边界判断 //最后一列,那么到了递归的结尾,直接计算即可 if (n - 1 == thisIndex) { //计算这种情况下总体的重量 int thisWeight = 0; for (int j = 0; j < n; j++) thisWeight += pWeight[j] * pCalc[j]; s.insert(thisWeight); //反正set会处理重复的 } else { //递归下一种情况,注意在递归处理下一种情况之前,后面的应该重视没有处理过 for (int j = thisIndex + 1; j < n; j++) pCalc[j] = 0; handleRes(n, pWeight, pNum, pCalc, thisIndex + 1); } }}int main(void){ //获取有关输入 int n; cin >> n; int* pWeight = new int[n]; int* pNum = new int[n]; int* pCalc = new int[n]; if (!pWeight || !pNum || !pCalc) return 1; for (int i = 0; i < n; i++) cin >> pWeight[i]; for (int i = 0; i < n; i++) { cin >> pNum[i]; pCalc[i] = 0; //放各种可能的数组先置空,表明都是放0个 } //开始处理,从下标为0的砝码开始处理 handleRes(n, pWeight, pNum, pCalc, 0); cout << s.size();#ifdef DEBUG while (true) cin.get();#endif}
转载于:https://www.cnblogs.com/jiayith/p/3923990.html