113. Path Sum II
Given the root
of a binary tree and an integer targetSum
, return all root-to-leaf paths where the sum of the node values in the path equals targetSum
. Each path should be returned as a list of the node values, not node references.
A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children.
targetSum
can be negative?
targetSum
can be any integer value including negative numbers.#include <vector>
using namespace std;
// Definition for a binary tree node.
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 {
public:
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
vector<vector<int>> result;
vector<int> currentPath;
findPaths(root, targetSum, currentPath, result);
return result;
}
private:
void findPaths(TreeNode* node, int targetSum, vector<int>& currentPath, vector<vector<int>>& result) {
if (!node) return;
currentPath.push_back(node->val);
if (!node->left && !node->right && targetSum == node->val) {
result.push_back(currentPath);
} else {
if (node->left) findPaths(node->left, targetSum - node->val, currentPath, result);
if (node->right) findPaths(node->right, targetSum - node->val, currentPath, result);
}
currentPath.pop_back(); // Backtrack
}
};
This solution effectively explores all potential paths in a binary tree to find those paths that equal the given targetSum
, using a depth-first search strategy complemented by backtracking.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?