LeetCode Question: 112. Path Sum (Level : Easy)
Problem Statement: 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.
Note:- Scroll horizontally to see the full line of code.
/**
*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
{
bool ans = false;
int targetSum;
public:
void preorder(TreeNode *root, int sum)
{
if (ans)
{
return;
}
sum += root->val;
if (sum == targetSum && !root->left && !root->right)
{
ans = true;
return;
}
if (root->left)
{
preorder(root->left, sum);
}
if (root->right)
{
preorder(root->right, sum);
}
}
bool hasPathSum(TreeNode *root, int targetSum)
{
this->targetSum = targetSum;
int sum = 0;
if (root)
{
preorder(root, sum);
}
return ans;
}
};
Comments
Post a Comment