Similar to the results of a previous analysis, you can use the DFS method to search for the enumerated possibilities.
Then we use the Backtracking Method to output the node.
Two points worth noting in this question are:
1: it must be a leaf node, but not an intermediate node.
2: For ordered output, switch the node so that the Left subtree is smaller
#include <stdio.h>#include <vector>using namespace std;struct Node{ int value,lchild,rchild;}nodes[10010];vector<int> result;void dfs(int count,int sum,int i){ if(i==-1) return ; if(sum==count+nodes[i].value&&nodes[i].lchild==-1&&nodes[i].rchild==-1) { result.push_back(i); printf("A path is found:"); for(int j=0;j<result.size();j++) printf(" %d",result[j]); printf("\n"); result.pop_back(); return; } if(sum>count+nodes[i].value) { result.push_back(i); dfs(count+nodes[i].value,sum,nodes[i].lchild); dfs(count+nodes[i].value,sum,nodes[i].rchild); result.pop_back(); }}int main(){ int num,sum; //freopen("data.in","r",stdin); while(scanf("%d%d",&num,&sum)!=EOF) { result.clear(); for(int i=1;i<=num;i++) { scanf("%d%d%d",&nodes[i].value,&nodes[i].lchild,&nodes[i].rchild); if(nodes[i].lchild>nodes[i].rchild) { int tmp=nodes[i].lchild; nodes[i].lchild=nodes[i].rchild; nodes[i].rchild=tmp; } } printf("result:\n"); dfs(0,sum,1); } return 0;}/************************************************************** Problem: 1368 User: vincent_ynh Language: C++ Result: Accepted Time:30 ms Memory:1140 kb****************************************************************/
9-degree question 1368: path of a binary tree and a specific value