#include <iostream>
#include <algorithm>
#include <queue>
#include <vector>
#include <cstring>
#include <stack>
#include <string>
#include <string.h>
#include <stdio.h>
#include <cmath>
#include <map>
#include <functional>
#include <set>
#include <math.h>
using namespace std;
//1368
int n,k,v,l,r;
struct node{
int d,l,r;
}node[10010];
vector<int> res;
void dfs(int cnt,int k,int i){
if(i==-1) return;
if(k==cnt+node[i].d && node[i].r==-1 && node[i].l==-1){ //路径和为k还要满足是叶子节点
res.push_back(i);
cout<<"A path is found:";
for(int j=0;j<res.size();j++)
cout<<" "<<res[j];
cout<<endl;
res.pop_back();
return;
}
if(cnt+node[i].d<k){
res.push_back(i);
dfs(cnt+node[i].d,k,node[i].l);
dfs(cnt+node[i].d,k,node[i].r);
res.pop_back();
}
}
int main(){
//freopen("input.txt","r",stdin);
while(cin>>n>>k){
res.clear();
for(int i=1;i<=n;i++){
cin>>node[i].d>>node[i].l>>node[i].r;
if(node[i].l>node[i].r)
swap(node[i].l,node[i].r);
}
cout<<"result:"<<endl;
dfs(0,k,1);
}
return 0;
}
/**************************************************************
Problem: 1368
User: cust123
Language: C++
Result: Accepted
Time:100 ms
Memory:1636 kb
****************************************************************/
题目1368:二叉树中和为某一值的路径
最新推荐文章于 2019-10-11 10:40:28 发布