基本思路:
- 寻找所有满足条件路径的二叉树遍历问题一律尝试用void返回值的dfs
- 正常的遍历模板,如果遍历到当前root->val==target时判断其是否为叶子节点,如果是则在res集合中添加一条路径;如果不是叶子节点,因为二叉树中可能有负数,所以从当前节点到叶子节点的路径可能为0,最终仍然得到一条满足条件的路径,所以还需要继续遍历而不能直接return。
class Solution { public: void dfs(vector<vector<int>>& res, vector<int>& path, TreeNode* root, int target) { if (!root) return; if (root->val == target) { if (!root->left && !root->right) { path.push_back(root->val); res.push_back(path); path.pop_back(); } } path.push_back(root->val); dfs(res, path, root->left, target - root->val); dfs(res, path, root->right, target - root->val); path.pop_back(); } vector<vector<int>> FindPath(TreeNode* root,int expectNumber) { vector<vector<int>> res; vector<int> path; dfs(res, path, root, expectNumber); return res; } };