What if you could instantly know if a path adds up to your target without checking every step yourself?
Why Path Sum Root to Leaf in Binary Tree in DSA C++?
Imagine you have a family tree drawn on paper, and you want to find if there is a path from the oldest ancestor to a youngest family member where the ages add up to a certain number.
Doing this by checking every possible path manually is tiring and confusing.
Manually adding ages along each path is slow and easy to make mistakes.
You might forget a branch or add wrong numbers, especially if the tree is big.
It's hard to keep track of all paths and sums without a clear method.
Using a program to check the tree automatically saves time and avoids errors.
The program walks down each path, adding numbers as it goes, and stops when it finds a path with the right sum.
This way, you get a clear yes or no answer quickly.
int sum = 0; // Manually add values for each path sum = 5 + 4 + 11 + 2; if (sum == target) return true;
bool hasPathSum(TreeNode* root, int targetSum) {
if (!root) return false;
if (!root->left && !root->right) return root->val == targetSum;
return hasPathSum(root->left, targetSum - root->val) || hasPathSum(root->right, targetSum - root->val);
}This lets you quickly find if any root-to-leaf path adds up to a target, even in big trees.
Checking if a route in a map has a total distance equal to a target number by adding distances between stops.
Manual checking is slow and error-prone.
Recursive path sum checking is fast and reliable.
Useful for any problem needing path sum verification in trees.
Practice
Solution
Step 1: Understand the problem statement
The problem asks if there is any path from the root node down to any leaf node where the sum of the node values equals a target sum.Step 2: Differentiate from other tree properties
It is not about depth, counting leaves, or total sum, but specifically about a path sum from root to leaf.Final Answer:
If there exists a root-to-leaf path with a sum equal to a given target -> Option BQuick Check:
Path sum means root-to-leaf sum check [OK]
- Confusing path sum with total tree sum
- Checking sum for any path, not root-to-leaf
- Counting nodes instead of summing values
Solution
Step 1: Check parameter types and return type
The function should take a pointer to the root node (TreeNode*) and an integer target sum, and return a boolean indicating if such a path exists.Step 2: Validate each option
bool hasPathSum(TreeNode* root, int targetSum) uses pointer and bool return type, which is correct. Options B and D pass TreeNode by value (less efficient), and B returns int, C returns void which is incorrect.Final Answer:
bool hasPathSum(TreeNode* root, int targetSum) -> Option DQuick Check:
Pointer input and bool output needed [OK]
- Passing node by value instead of pointer
- Using wrong return type like void or int
- Missing pointer symbol (*) in parameter
#include <iostream>
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
bool hasPathSum(TreeNode* root, int targetSum) {
if (!root) return false;
if (!root->left && !root->right) return root->val == targetSum;
return hasPathSum(root->left, targetSum - root->val) || hasPathSum(root->right, targetSum - root->val);
}
int main() {
TreeNode* root = new TreeNode(5);
root->left = new TreeNode(4);
root->right = new TreeNode(8);
root->left->left = new TreeNode(11);
root->left->left->left = new TreeNode(7);
root->left->left->right = new TreeNode(2);
root->right->left = new TreeNode(13);
root->right->right = new TreeNode(4);
root->right->right->right = new TreeNode(1);
bool result = hasPathSum(root, 22);
std::cout << (result ? "true" : "false") << std::endl;
return 0;
}Solution
Step 1: Trace the path sums in the tree
Check if any root-to-leaf path sums to 22. One path is 5->4->11->2 = 22.Step 2: Confirm function logic and output
The function correctly returns true if such a path exists. The code prints "true".Final Answer:
true -> Option AQuick Check:
Path 5+4+11+2 = 22 found [OK]
- Ignoring leaf node condition
- Subtracting values incorrectly
- Assuming no path matches without checking all
bool hasPathSum(TreeNode* root, int targetSum) {
if (root == nullptr) return false;
if (root->left == nullptr && root->right == nullptr) return targetSum == root->val;
return hasPathSum(root->left, targetSum) || hasPathSum(root->right, targetSum);
}Solution
Step 1: Analyze recursive calls
The function calls itself with the same targetSum without subtracting the current node's value, so it never reduces the sum along the path.Step 2: Identify correct recursive logic
It should call hasPathSum(root->left, targetSum - root->val) and similarly for right to correctly track remaining sum.Final Answer:
The targetSum is not reduced by root->val in recursive calls -> Option CQuick Check:
Subtract node value each step [OK]
- Not updating targetSum in recursive calls
- Confusing base case return values
- Returning wrong data type
Solution
Step 1: Consider negative values in path sum
The standard recursive algorithm subtracts the current node's value (which can be negative) from the targetSum at each step, correctly handling negatives, zeros, and positives for root-to-leaf paths.Step 2: No change required
The problem is specifically for root-to-leaf paths, not arbitrary paths, so no modification is needed.Final Answer:
No modification needed; the standard path sum check works for all values -> Option AQuick Check:
Recursion handles negatives via subtraction [OK]
- Thinking negatives require checking all paths
- Using global variables unnecessarily
- Changing return type without reason
Ready to prove it?
Pass the test and this pattern moves unknown
