Created
June 29, 2013 21:42
-
-
Save barrysteyn/5892792 to your computer and use it in GitHub Desktop.
LeetCode: HasPathSum
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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