result:
推荐指数:※※
来源:http://ac.jobdu.com/problem.php?pid=1368
这与PAT的http://blog.csdn.net/zhu_liangwei/article/details/9735741类似。
#include<iostream> #include<stdio.h> #include<stdlib.h> #include<vector> using namespace std; #define max(a,b) ((a)>(b)?(a):(b)) #define min(a,b) ((a)<(b)?(a):(b)) typedef struct node{ int val; int left; int right; }node; vector<int> path; void print_path(){ printf("A path is found:"); for(int i=0;i<path.size();i++){ printf(" %d",path[i]); } printf("\n"); } void find_fit_path(int curr,int i,const node *t){ if(i!=-1&&t[i].val==curr&&-1==t[i].left&&-1==t[i].right){ path.push_back(i); print_path(); path.pop_back(); } else if(t[i].val<curr){ int tmp=min(t[i].left,t[i].right); path.push_back(i); if(tmp!=-1) find_fit_path(curr-t[i].val,tmp,t); tmp=max(t[i].left,t[i].right); if(tmp!=-1) find_fit_path(curr-t[i].val,tmp,t); path.pop_back(); } } int main() { int n,k,i; while(scanf("%d%d",&n,&k)!=EOF){ node *tree=new node[n+1]; for(i=1;i<=n;i++) scanf("%d%d%d",&tree[i].val,&tree[i].left,&tree[i].right); printf("result:\n"); find_fit_path(k,1,tree); } }