Root to leaf sum.
I:
class Solution {
public:
bool hasPathSum(TreeNode *root, int sum) {
if (!root) return false;
if ((!root->left) && (!root->right) && root->val==sum) return true;
return hasPathSum(root->left, sum-root->val) || hasPathSum(root->right, sum-root->val);
}
};II:
If we use cur.pop_back() at the end of the function, then we do not need to backup the current vector.
class Solution {
public:
void dfs(TreeNode *root, int sum, vector<int> &cur, vector<vector<int> > &res) {
if (!root) return;
cur.push_back(root->val);
vector<int> backup(cur);
if ((!root->left) && (!root->right) && root->val==sum) {
res.push_back(cur);
return;
}
dfs(root->left, sum-root->val, cur, res);
cur=backup;
dfs(root->right, sum-root->val, cur, res);
}
vector<vector<int> > pathSum(TreeNode *root, int sum) {
vector<int> cur;
vector<vector<int> > res;
dfs(root, sum, cur, res);
return res;
}
};
373

被折叠的 条评论
为什么被折叠?



