又是关于二叉树的算法,由于不知道节点是否能包含负值,所以我们默认节点值可能为负,因此必须遍历从头节点到叶节点的每一条路劲,即穷举。
很容易想到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 {
vector<vector<int>> ans;
void dfs(TreeNode* root, vector<int> &trace, int sum) {
if (!root) { // 出口
return;
}
trace.emplace_back(root->val);
sum -= root->val;
if (!root->left && !root->right && !sum) {
ans.emplace_back(trace);
}
dfs(root->left, trace, sum);
dfs(root->right, trace, sum);
trace.pop_back(); // 回退
// sum += root->val 由于sum是局部变量,不会改变原值,所以无需回退
}
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<int> trace;
dfs(root, trace, sum);
return ans;
}
};
结果: