給定一個二叉樹,它的每個結點都存放著一個整數值。
找出路徑和等于給定數值的路徑總數。
路徑不需要從根節點開始,也不需要在葉子節點結束,但是路徑方向必須是向下的(只能從父節點到子節點)。
二叉樹不超過1000個節點,且節點數值范圍是 [-1000000,1000000] 的整數。
示例:
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 810/ \5 -3/ \ \3 2 11/ \ \ 3 -2 1返回 3。和等于 8 的路徑有:1. 5 -> 3 2. 5 -> 2 -> 1 3. -3 -> 11
class Solution {
public:void helper(TreeNode *root, int sum, vector<int> &s, int &res){if (!root) return ;s.push_back(root->val);int t = 0;for (int i = s.size()-1; i >=0; i--){t += s[i];if (t == sum) res++;}helper(root->left, sum, s, res);helper(root->right, sum, s, res);s.pop_back();}int pathSum(TreeNode* root, int sum) {int res = 0;vector<int> s;helper(root, sum, s, res);return res;}
};
?