题意
输入一棵二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。
题解
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
vector<vector<int>> res;
vector<int> path;
int sum;
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
this->sum = sum;
recur(root, 0);
return res;
}
void recur(TreeNode* root, int num){
if(root == NULL) return;
num += root->val;
path.push_back(root->val);
if(num == sum && root->left == NULL && root->right == NULL)
res.push_back(path);
recur(root->left, num);
recur(root->right, num);
path.pop_back();
}
};