题目1368:二叉树中和为某一值的路径

#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
****************************************************************/

JZ34题目要求我们 在给定的二叉树所有和为指定路径。这道题是JZ24二叉树和为某一值路径的加强版,因为它需要我们找所有符合要求的路径,而不是从根节点到叶节点的一条路径。 我们可以采用深度优先遍历(DFS)的方法来解决这个问题。具体做法如下: 1. 首先我们需要定义一个函数,用于遍历二叉树: ```python def dfs(node, target, path, result): # node表示当前遍历的节点 # target表示剩余的目标 # path表示当前已选择的路径 # result表示符合要求的路径列表 # 如果遍历到了空节点,直接返回 if not node: return # 把当前节点添加到路径 path.append(node.val) # 计算当前剩余的目标 target -= node.val # 如果目标为0,说明找到了一条符合要求的路径,将其加入结果列表 if target == 0 and not node.left and not node.right: result.append(path[:]) # 继续递归遍历左右子树 dfs(node.left, target, path, result) dfs(node.right, target, path, result) # 回溯,将刚刚添加的节点从路径删除 path.pop() ``` 2. 然后我们需要遍历整个二叉树,对于每个遍历到的节点,都调用一次`dfs`函数,将其作为先前路径的一部分,并且更新`target`的: ```python def find_path(root, target): result = [] dfs(root, target, [], result) return result ``` 这样,我们就可以得到所有符合要求的路径了。 总之,这道题需要我们具备二叉树基础知识和DFS基础知识,我们需要仔细阅读题目并思考,再将自己的思路转化为代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值