AcWing 47. 二叉树中和为某一值的路径
原题链接
中等
作者:
跟着灿哥学切菜
,
2021-02-01 16:56:59
,
所有人可见
,
阅读 263
/**
* 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>> ans;
vector<int> path;
vector<vector<int>> findPath(TreeNode* root, int sum) {
dfs(root, sum);
return ans;
}
void dfs(TreeNode* root, int sum) {
//如果当前节点是空的, 此时表示该节点不是叶子节点
if (!root) return;
path.push_back(root -> val);
sum -= root -> val;
//如果当前节点的左右孩子节点都是空的, 此时就是叶子节点
if (!root -> left && !root -> right && !sum) ans.push_back(path); //将当前路径加到答案中
//递归处理左右孩子节点
dfs(root -> left, sum);
dfs(root -> right, sum);
path.pop_back();
}
};