二叉树的路径之和

题目:
给定一个二叉树与正数sum,找出所有从根节点到叶节点的路径,这些路径上的节点值累加和为sum。

#include<stdio.h>
#include<vector>
using namespace std;

struct TreeNode{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x):val(x),left(NULL),right(NULL){}
};

class Solution{
    public:
        vector<vector<int> > path_sum(TreeNode* root,int sum){
            vector<vector<int> > result;
            vector<int> path;
            int path_value=0;
            preorder(root,path_value,sum,path,result);
            return result;
        }
    private:
    //只有定义方法的时候才写数据类型,用的时候不用写
        void preorder(TreeNode *node,int &path_value,int sum,vector<int> &path,vector<vector<int> > &result){
            if(!node){
                return;
            }
            path_value+=node->val;
            path.push_back(node->val);
            if(!node->left&&!node->right&&path_value==sum){
                result.push_back(path);
            }
            preorder(node->left,path_value,sum,path,result);
            preorder(node->right,path_value,sum,path,result);
            path_value-=node->val;
            path.pop_back();
        }
};

int main(){

    TreeNode a(5);
    TreeNode b(4);
    TreeNode c(8);
    TreeNode d(11);
    TreeNode e(13);
    TreeNode f(4);
    TreeNode g(7);
    TreeNode h(2);
    TreeNode x(5);
    TreeNode y(1);
    a.left=&b;
    a.right=&c;
    b.left=&d;
    c.left=&e;
    c.right=&f;
    d.left=&g;
    d.right=&h;
    f.left=&x;
    f.right=&y;

    Solution solve;
    vector<vector<int> > result=solve.path_sum(&a,22);
    for(int i=0;i<result.size();i++){
        for(int j=0;j<result[i].size();j++){
            printf("[%d]",result[i][j]);
        }
        printf("\n");
    }

    return 0;
}

答案:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值