Skip to main content

112. Path Sum

  • Recursion
/**
* 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:
bool hasPathSum(TreeNode* root, int targetSum)
{
if (!root) return false;

targetSum -= root->val;

if (!root->left && !root->right) return targetSum == 0;

return hasPathSum(root->left, targetSum) || hasPathSum(root->right, targetSum);
}
};
  • T: O(N)O(N)

  • S: O(N)O(N)

  • Iteration

/**
* 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:
bool hasPathSum(TreeNode* root, int targetSum)
{
if (!root) return false;
queue<pair<TreeNode*, int>> q;
q.push({root, targetSum});
while (!q.empty())
{
TreeNode* node = q.front().first;

int sum = q.front().second; q.pop();

if (!node) continue;

sum -= node->val;

if (sum == 0 && !node->left && !node->right)
{
return true;
}

if (node->left)
{
q.push({node->left, sum});
}

if (node->right)
{
q.push({node->right, sum});
}
}
return false;
}
};
  • T: O(N)O(N)
  • S: O(N)O(N)