9-degree question 1368: path of a binary tree and a specific value

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.