Path Sum II Solutions in C++
Number 113
Difficulty Medium
Acceptance 46.9%
Link LeetCode
Solutions
C++ solution by haoel/leetcode
// Source : https://oj.leetcode.com/problems/path-sum-ii/// Author : Hao Chen// Date : 2014-07-01/*** Definition for binary tree* 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> > result;vector<int> v;generatePathSum(root, sum, 0, v, result);return result;}void generatePathSum(TreeNode *root, int sum, int s, vector<int> v, vector<vector<int> >& result) {if (root==NULL) return ;s += root->val;v.push_back(root->val);if ( root->left==NULL && root->right==NULL) {if (s == sum) result.push_back(v);return;}generatePathSum(root->left, sum, s, v, result);generatePathSum(root->right, sum, s, v, result);}};
C++ solution by pezy/LeetCode
#include <vector>#include <cstddef>#include <stack>#include <algorithm>using std::vector;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>> ret;vector<int> path;pathSum(root, sum, path, ret);return ret;}void pathSum(TreeNode *root, int sum, vector<int> &path, vector<vector<int>> &ret) {if (!root) return;path.push_back(root->val);if (!root->left && !root->right && root->val == sum) ret.push_back(path);if (root->left) pathSum(root->left, sum-root->val, path, ret);if (root->right) pathSum(root->right, sum-root->val, path, ret);path.pop_back();}};
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/path-sum-ii/description//// Author : liuyubobobo/// Time : 2018-10-16#include <iostream>#include <vector>using namespace std;/// Recursion/// Time Complexity: O(n)/// Space Complexity: O(n)/// 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;if(!root)return res;vector<int> tres;dfs(root, tres, 0, sum, res);return res;}private:void dfs(TreeNode* node, vector<int>& tres, int tsum,int sum, vector<vector<int>>& res){tres.push_back(node->val);tsum += node->val;if(!node->left && !node->right){if(tsum == sum)res.push_back(tres);}else {if (node->left)dfs(node->left, tres, tsum, sum, res);if (node->right)dfs(node->right, tres, tsum, sum, res);}tres.pop_back();return;}};int main() {return 0;}