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//\11134/\/\7251
Return:
[
[5,4,11,2],
[5,8,4,5]
]
给定一棵二叉树,求问有没有一条从根节点到子节点额路径,各val值加起来等于sum。
与112题不同之处在于,要写明这条路径的所有节点的值。
采用回溯法,首先建立作为返回值的res数组,接着建立临时vector存储当前遍历路径的具体数值,若到达子节点,不符合条件,则清空临时vector;若符合条件,则将临时vector存入res数组中。
/**
* 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> temp;
dfs(root, res, temp, sum);
return res;
}
void dfs(TreeNode* root, vector<vector<int>>& res, vector<int>& temp, int sum){
if(!root) return;
temp.push_back(root->val);
int cur = sum - root->val;
if(!root->left && !root->right && cur == 0){
res.push_back(root->val);
temp.pop_back();
return;
}
if(!root->left && !root->right && cur != 0){
temp.pop_back();
return;
}
dfs(root->left, res, temp, sum-root->val);
dfs(root->right, res, temp, sum-root->val);
temp.pop_back();
return;
}
};