Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.html
Note: A leaf is a node with no children.node
Example:数组
Given the below binary tree and sum = 22
,函数
5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1
Return:spa
[ [5,4,11,2], [5,8,4,5] ]
和Path Sum的思路同样,连接在这里http://www.javashuo.com/article/p-rluaxasn-gw.html。code
只不过这道题须要将知足目标和的路径打印出来,咱们能够传入一个空数组,每执行一次函数,便将当前的元素,也就是root->val加入到数组,当知足条件时,将数组传入进咱们定义好的结果数组当中,须要注意的是,空数组须要传参,而不是传引用。htm
/** * 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>> pathSum(TreeNode* root, int sum) { vector<vector<int>> res; vector<int> s; dfs(root, sum, s, res); return res; } void dfs(TreeNode* root, int sum, vector<int> s, vector<vector<int>> &res){ if(root == nullptr) return; s.push_back(root->val); if(root->left == nullptr && root->right == nullptr){ if(sum == root->val) res.push_back(s); } else{ dfs(root->left, sum-root->val, s, res); dfs(root->right, sum-root->val, s, res); } } };