Skip to content

Commit

Permalink
LeetCode: 113. Path Sum II
Browse files Browse the repository at this point in the history
- accepted;
  • Loading branch information
olegon committed Aug 20, 2023
1 parent 0305035 commit 1f5e945
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
5 changes: 5 additions & 0 deletions leetcode/problems/path-sum-ii/compile-and-run.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#!/bin/bash

set -x

clang++ main.cpp -W -Wall -std=c++17 -O2 -fsanitize=address && ./a.out
47 changes: 47 additions & 0 deletions leetcode/problems/path-sum-ii/main.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
113. Path Sum II
https://leetcode.com/problems/path-sum-ii
*/

#include <bits/stdc++.h>

using namespace std;

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 {
private:
void pathSum(TreeNode* node, int targetSum, vector<int> &currentPath, vector<vector<int>> &paths) {
currentPath.push_back(node->val);

if (node->left == nullptr && node->right == nullptr && node->val == targetSum) paths.push_back(currentPath);
if (node->left != nullptr) pathSum(node->left, targetSum - node->val, currentPath, paths);
if (node->right != nullptr) pathSum(node->right, targetSum - node->val, currentPath, paths);

currentPath.pop_back();
}
public:
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
vector<vector<int>> paths;

if (root != nullptr) {
vector<int> currentPath;
pathSum(root, targetSum, currentPath, paths);
}

return paths;
}
};

int main(void) {
ios::sync_with_stdio(false);

return EXIT_SUCCESS;
}

0 comments on commit 1f5e945

Please sign in to comment.