给定一个二叉树和一个和,找到所有从根到叶路径总和等于给定总和的路径。
例如,
给定下面的二叉树和 sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
返回
[
[5,4,11,2],
[5,8,4,5]
]
详见:https://leetcode.com/problems/path-sum-ii/description/
/** * 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 { public: vector<vector<int>> pathSum(TreeNode* root, int sum) { vector<vector<int>> res; vector<int> path; if(root==nullptr) { return res; } findPath(root,sum,path,res); return res; } void findPath(TreeNode* root,int sum,vector<int> &path,vector<vector<int>> &res) { if(root==nullptr) { return; } path.push_back(root->val); if(root->val==sum&&root->left==nullptr&&root->right==nullptr) { res.push_back(path); path.pop_back(); } else { findPath(root->left,sum-root->val,path,res); findPath(root->right,sum-root->val,path,res); path.pop_back(); } } };