关于递归的各种操作

来源:互联网 发布:js中json转数组 编辑:程序博客网 时间:2024/05/22 00:30

现在说说,现在说说

struct Node{Node* left;Node* right;int val;Node(int a):val(a){left=NULL;right=NULL;}};//获得整棵树的深度int GetDepth(Node* root){if(NULL==root){return 0;}int lDepth=GetDepth(root->left);int rDepth=GetDepth(root->right);return lDepth>rDepth?lDepth+1:rDepth+1;}int GetNodeDepth(Node* root,Node* value,int layer){int i=-1;if(root){if(root==value){return layer;}if((i=GetNodeDepth(root->left,value,layer+1))!=-1){return i;}if((i=GetNodeDepth(root->right,value,layer+1))!=-1){return i;}}return i;}void BSF(Node* root){deque<Node*> deq;deq.push_back(root);while(!deq.empty()){Node* tmp=deq.front();deq.pop_back();if(tmp->left){deq.push_back(tmp->left);}if(tmp->right){deq.push_back(tmp->right);}}}void printAllPath(Node* root,vector<Node*>&m_vec){if(NULL!=root){m_vec.push_back(root);if(NULL==root->left&&NULL==root->right){//已经获得所有的路径vector<Node*>::iterator itr=m_vec.begin();for(;itr!=m_vec.end();itr++){cout<<(*itr)->val<<"  ";}cout<<endl;}else{printAllPath(root->left,m_vec);printAllPath(root->right,m_vec);}m_vec.pop_back();}}int main(){Node* root=new Node(5);root->left=new Node(4);Node* cur=root->right=new Node(10);root->left->left=new Node(1);root->left->right=new Node(23);root->right->right=new Node(89);int d=GetNodeDepth(root,cur,0);cout<<d<<endl;vector<Node*> m_vec;printAllPath(root,m_vec);}

关于兑换零钱的策略

int g_max=6;int g_num=3;void compute_probably(int orignal,int current,int value,int tmpsum,int*pProbably){if(1==current){int sum=tmpsum+value;pProbably[sum-orignal]++;}else{for(int i=1;i<=g_max;i++){int sum=tmpsum+a[i];compute_probably(orignal,current-1,a[i],sum,pProbably);}}}int main(){int sum=g_max*g_num;//获得有可能的所有数字的可能性数组int*pProbably=new int[sum-g_max+1];memset(pProbably,0,sum-g_max+1);for(int i=1;i<=g_num;i++){compute_probably(g_num,g_num,i,0,pProbably);}}void getCount(int sum,int index){if(sum>money){return;}if(sum==money){nj++;}else{for(int i=index;i<sizeof(a)/4;i++){tmp[i]++;getCount(sum+a[i],i);tmp[i]--;}}}void pailie (char* str,char* pBegin){if(*pBegin=='\0'){cout<<str<<endl;return;}for(char* index=pBegin;*index!='\0';index++){char m=*index;*index=*pBegin;*pBegin=m;pailie(str,index+1);m=*index;*index=*pBegin;*pBegin=m;}}


0 0
原创粉丝点击