剑指 Offer 34. 二叉树中和为某一值的路径
给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。
叶子节点 是指没有子节点的节点。
示例 1:
输入:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
输出:[[5,4,11,2],[5,8,4,5]]
输入:root = [1,2,3], targetSum = 5
输出:[]
示例 3:
输入:root = [1,2], targetSum = 0
输出:[]
class Solution:
def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
res, path = [], []
def recur(root, tar):
if not root: return
path.append(root.val)
tar -= root.val
if tar == 0 and not root.left and not root.right:
res.append(list(path))
recur(root.left, tar)
recur(root.right, tar)
path.pop()
recur(root, sum)
return res
class Solution {
public:
void def(TreeNode* root, int target, vector<vector<int>> &vec, vector<int> &vec1)
{
if(root == nullptr)
return;
vec1.push_back(root->val);
target -= root->val;
if(target == 0 && root->left== nullptr && root->right == nullptr)
vec.push_back(vec1);
def(root->left, target, vec, vec1);
def(root->right, target, vec, vec1);
vec1.pop_back();
}
vector<vector<int>> pathSum(TreeNode* root, int target) {
vector<vector<int>> vec;
vector<int> vec1;
def(root, target, vec, vec1) ;
return vec;
}
};
def(root, target, vec, vec1) ;
return vec;
}
};