From 80701ab517aee7c4d41e550a97c396caca4c1489 Mon Sep 17 00:00:00 2001 From: moophis Date: Sat, 18 Oct 2014 14:23:24 -0700 Subject: [PATCH] Path Sum: refactor code --- Path Sum.cpp | 36 +++++++++--------------------------- 1 file changed, 9 insertions(+), 27 deletions(-) diff --git a/Path Sum.cpp b/Path Sum.cpp index 8a73150..9219a52 100644 --- a/Path Sum.cpp +++ b/Path Sum.cpp @@ -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); } }; \ No newline at end of file