遇到此问题的时候,如果运行递归要返回值的话,一般可以这样写 return 后面接递归的函数。
题目一:数字在排序数组中出现的次数
class Solution { public: int GetNumberOfK(vector<int> data ,int k) { int number=0; if(data.size()!=0){ int first=GetFirstk(data,k,0,data.size()-1); int last=GetLastk(data,k,0,data.size()-1); if(first>-1&&last>-1)number=last-first+1; } return number; } int GetFirstk(vector<int>&data,int k,int start,int end){ if(start>end)return -1; int mid=(start+end)>>1; if(data[mid]==k){ if((mid>0&&data[mid-1]!=k)||mid==0)return mid; else return GetFirstk(data,k,start,mid-1); } else{ if(data[mid]>k)return GetFirstk(data,k,start,mid-1); else return GetFirstk(data,k,mid+1,end); } } int GetLastk(vector<int>&data,int k,int start,int end){ if(start>end)return -1; int mid=(start+end)>>1; if(data[mid]==k){ if((mid<data.size()&&data[mid+1]!=k)||(mid==data.size()-1))return mid; else return GetLastk(data,k,mid+1,end); } else{ if(data[mid]<k)return GetLastk(data,k,mid+1,end); else return GetLastk(data,k,start,mid-1); } } };
题目二:二叉树的深度
class Solution { public: int TreeDepth(TreeNode* pRoot) { if(!pRoot)return 0; return max(TreeDepth(pRoot->left),TreeDepth(pRoot->right))+1; } };
原文地址:https://www.cnblogs.com/inception6-lxc/p/9296529.html
时间: 2024-10-06 06:10:38