题目
输入一棵二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。
示例:
给定如下二叉树,以及目标和 target = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
返回:
[
[5,4,11,2],
[5,8,4,5]
]
提示:
- 节点总数 <= 10000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
DFS题,用一个数组path存当前遍历到的路径,当抵达叶节点且和为target的时候将path存入结果ans数组中。递归时可以在经过一个节点时用target的值减去该节点的值,这样最后只需要判断target是否为0即可,用传值的方法传target。记得使用标记清除。
时间复杂度\(O(n^2)\),空间复杂度O(n)。
代码
/**
* 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 {
public:
vector<vector<int>> ans;
vector<int> path;
vector<vector<int>> pathSum(TreeNode* root, int target) {
if(!root) return ans;
path.push_back(root->val);
dfs(root, ans, path, target - root->val);
return ans;
}
void dfs(TreeNode *cur, vector<vector<int>>& ans, vector<int>& path, int target)
{
if(target == 0 && !cur->left && !cur->right)
{
ans.push_back(path);
return;
}
if(cur->left)
{
path.push_back(cur->left->val);
dfs(cur->left, ans, path, target - cur->left->val);
path.pop_back();
}
if(cur->right)
{
path.push_back(cur->right->val);
dfs(cur->right, ans, path, target - cur->right->val);
path.pop_back();
}
}
};