**(leetcode) (tree) Path Sum II

来源:互联网 发布:男人越大越好吗知乎 编辑:程序博客网 时间:2024/05/22 06:32

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

For example:
Given the below binary tree and sum = 22,
              5             / \            4   8           /   / \          11  13  4         /  \    / \        7    2  5   1

return

[   [5,4,11,2],   [5,8,4,5]]
思路: 每条路径都给一个vector存储即可
/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {    void path(TreeNode *root, vector<vector<int> > &result, vector<int> v, int sum){        if(root==NULL)            return;        v.push_back(root->val);        vector<int> v1(v);        sum-=root->val;        if(sum==0&&root->left==NULL&&root->right==NULL)           result.push_back(v);        else{            path(root->left, result, v, sum);            path(root->right, result, v1, sum);        }    }public:    vector<vector<int> > pathSum(TreeNode *root, int sum) {        vector<vector<int> > result;        vector<int> v;        path(root, result, v, sum);        return result;    }};

0 0
原创粉丝点击