题目:
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
Note: A leaf is a node with no children.
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] ]
分析:
和Path Sum的思路一样,链接在这里https://www.cnblogs.com/silentteller/p/10823183.html。
只不过这道题需要将满足目标和的路径打印出来,我们可以传入一个空数组,每执行一次函数,便将当前的元素,也就是root->val加入到数组,当满足条件时,将数组传入进我们定义好的结果数组当中,需要注意的是,空数组需要传参,而不是传引用。
程序:
/** * 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); } } };