leetcode---Path Sum II---回溯

来源:互联网 发布:linux常用命令实例详解 编辑:程序博客网 时间:2024/05/21 03:59

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,
这里写图片描述
return
[
[5,4,11,2],
[5,8,4,5]
]

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    vector<vector<int>> ans;    void solve(TreeNode* root, int now, vector<int> tmp, int sum)    {        if(root == NULL)            return;        tmp.push_back(root->val);        now += root->val;        if(now == sum && root->left == NULL && root->right == NULL)        {            ans.push_back(tmp);        }        solve(root->left, now, tmp, sum);        solve(root->right, now, tmp, sum);        tmp.pop_back();        now -= root->val;        return;    }    vector<vector<int>> pathSum(TreeNode* root, int sum)     {        vector<int> tmp;        solve(root, 0, tmp, sum);        return ans;    }};
0 0