Path Sum
LeetCode #112 · Easy · Trees · C++ solution with worked-out approach and complexity analysis.
Approach
Iterative DFS using Stack
Use a stack to store pairs of (node, currentSum). For each node, track the sum from root to that node. When we reach a leaf node, check if the currentSum equals targetSum.
Time
O(n)
visit each node at most once
Space
O(h)
h is the height of the tree (stack space)
Problem description(from LeetCode)
Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum. A leaf is a node with no children.
Examples
Example 1
- Input:
- root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
- Output:
- true
- Note:
- The path with the target sum is shown.
Example 2
- Input:
- root = [1,2,3], targetSum = 5
- Output:
- false
- Note:
- There are two root-to-leaf paths in the tree: (1 -> 2): The sum is 3. (1 -> 3): The sum is 5. There is no root-to-leaf path with sum = 5.
Example 3
- Input:
- root = [], targetSum = 0
- Output:
- false
- Note:
- Since the tree is empty, there are no root-to-leaf paths.
Constraints
- •The number of nodes in the tree is in the range [0, 5000].
- •-1000 <= Node.val <= 1000
- •-1000 <= targetSum <= 1000
C++ Solution
solution.cpp
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:
bool hasPathSum(TreeNode *root, int targetSum) {
if (root == nullptr) return false;
stack<pair<TreeNode *, int>> s;
s.push({root, root->val});
while (!s.empty()) {
pair<TreeNode *, int> top = s.top();
s.pop();
TreeNode *node = top.first;
int currentSum = top.second;
if (node->left == nullptr && node->right == nullptr &&
currentSum == targetSum) {
return true;
}
if (node->right != nullptr) {
s.push({node->right, currentSum + node->right->val});
}
if (node->left != nullptr) {
s.push({node->left, currentSum + node->left->val});
}
}
return false;
}
};