题目描述
给你二叉树的根节点 root
和一个整数目标和 targetSum
,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。
叶子节点 是指没有子节点的节点。
题目来源:力扣
题解
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
vector<vector<int>> ans; int tar; class Solution { public: void dfs(TreeNode* u, vector<int>& path, int val) { if (u == nullptr) return ; path.push_back(u->val); val += u->val; if (val == tar && u->left == nullptr && u->right == nullptr) { ans.push_back(path); path.pop_back(); return ; } dfs(u->left, path, val); dfs(u->right, path, val); path.pop_back(); } vector<vector<int>> pathTarget(TreeNode* root, int target) { tar = target; ans.clear(); vector<int> ret; dfs(root, ret, 0); return ans; } };
|