Leetcode - path sum系列
path sum I
DFS+判断
https://leetcode.com/problems/path-sum/
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if (!root) return false;
return dfs(root, sum);
}
bool dfs(TreeNode *root, int sum) {
if (!root) return false;
sum -= root->val;
if (!root->right && !root->left) return sum == 0;
return dfs(root->right, sum) | dfs(root->left, sum);
}
};
path sum II
dfs + backtracking, 如何恢复现场
class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int>> res; vector<int> v;
dfs(root, sum, v, res);
return res;
}
void dfs(TreeNode *root, int sum, vector<int>& v, vector<vector<int>>& res) {
if (!root) return;
sum -= root->val;
v.push_back(root->val);
if (sum == 0 && !root->left && !root->right) res.push_back(v);
dfs(root->left, sum, v, res);
dfs(root->right, sum, v, res);
v.pop_back();
}
};
path sum III
每个点都要dfs俩次,一次是remaining sum, 一次是sum。 因此help要递归,主函数也要递归。 => 用queue操作也ok
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
int cnt = 0;
public:
int pathSum(TreeNode* root, int sum) {
if (!root) return 0;
dfs(root, sum, cnt);
pathSum(root->left, sum);
pathSum(root->right, sum);
return cnt;
}
void dfs(TreeNode *root, int sum, int & cnt) {
if (!root) return;
if (root->val == sum) cnt++;
dfs(root->left, sum-root->val, cnt);
dfs(root->right, sum-root->val, cnt);
}
};