题目描述:
输入一棵二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。
示例:
给定如下二叉树,以及目标和 target = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
返回:
[
[5,4,11,2],
[5,8,4,5]
]
提示:
节点总数 <= 10000
解题思路:
本题可以采用深度优先搜索DFS来解决,按照先序遍历的方案遍历所有的路径,遍历的同时记录所经过路径的和,直到当前节点为叶子节点且路径和为目标值
/**
* 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 {
private:
vector<int> path;
vector<vector<int>> result;
public:
vector<vector<int>> pathSum(TreeNode* root, int target) {
dfs(root,target);
return result;
}
void dfs(TreeNode* root, int target){
if(root != nullptr){
int temp = target - root->val;
path.push_back(root->val);
if(temp != 0 || root->left != nullptr || root->right != nullptr){
dfs(root->left, temp);
dfs(root->right,temp);
}else{
result.push_back(path);
}
path.pop_back();
}
}
};