1.路径总和II
思路一:DFS
我们可以采用深度优先搜索的方式,枚举每一条从根节点到叶子节点的路径。当我们遍历到叶子节点,且此时路径和恰为目标和时,我们就找到了一条满足条件的路径。
/**
* 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>> ret;//总路径
vector<int> path;//单条路径
void dfs(TreeNode* root, int sum) {
if (root == nullptr) {
return;
}
path.emplace_back(root->val);
sum -= root->val;
if (root->left == nullptr && root->right == nullptr && sum == 0) {
ret.emplace_back(path);
}//放入一条路径的条件
dfs(root->left, sum);
dfs(root->right, sum);
path.pop_back();
}
vector<vector<int>> pathSum(TreeNode* root, int sum) {
dfs(root, sum);
return ret;
}
};
京公网安备 11010502036488号