Skip to content

Instantly share code, notes, and snippets.

@barrysteyn
Created June 29, 2013 21:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barrysteyn/5892792 to your computer and use it in GitHub Desktop.
Save barrysteyn/5892792 to your computer and use it in GitHub Desktop.
LeetCode: HasPathSum
/**
* Things to ask in an interview: Can sum ever be zero
* Time: O(n) (n = number of nodes)
*/
class Solution {
public:
bool hasPathSum(TreeNode *root, int sum) {
if (!root) {
return false;
}
if (sum - root->val == 0 && !root->right && !root->left) {
return true;
}
bool hasPath = hasPathSum(root->left, sum-root->val);
if (hasPath) return true;
hasPath = hasPathSum(root->right, sum-root->val);
return hasPath;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment