Skip to content

Commit

Permalink
Path Sum: refactor code
Browse files Browse the repository at this point in the history
  • Loading branch information
moophis committed Oct 18, 2014
1 parent 35d7ad3 commit 80701ab
Showing 1 changed file with 9 additions and 27 deletions.
36 changes: 9 additions & 27 deletions Path Sum.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,38 +25,20 @@
* };
*/
class Solution {
bool find_path(TreeNode *root, int sum, int cur) {
if (root->left == nullptr && root->right == nullptr) {
return sum == cur + root->val;
bool find_sum(TreeNode *root, const int sum, int cur) {
if (root == nullptr) {
return false;
}

bool left_match = false;
bool right_match = false;

if (root->left != nullptr) {
left_match = find_path(root->left, sum, cur + root->val);
if (left_match) {
return true;
}
cur += root->val;
if (root->left == nullptr && root->right == nullptr) {
return (sum == cur);
}
if (root->right != nullptr) {
right_match = find_path(root->right, sum, cur + root->val);
if (right_match) {
return true;
}
}

return false;
return find_sum(root->left, sum, cur) || find_sum(root->right, sum, cur);
}

public:
bool hasPathSum(TreeNode *root, int sum) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if (root == nullptr) {
return false;
}

int cur = 0;
return find_path(root, sum, cur);
return find_sum(root, sum, 0);
}
};

0 comments on commit 80701ab

Please sign in to comment.