描述
输入一棵二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。

题解
这道题的具体解法,可参看 Krahets的题解
/*** 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<int> path;vector<vector<int>> result;vector<vector<int>> pathSum(TreeNode* root, int target) {dfs(root, target);return result;}void dfs(TreeNode* root, int target) {if(root == nullptr) return;path.push_back(root->val);target -= root->val;if(target == 0 && root->left == nullptr && root->right == nullptr) {result.emplace_back(path); // emplace_back 是 push_back 的性能优化版方法}dfs(root->left, target);dfs(root->right, target);path.pop_back();}};
