static bool _hasPathSum(Node<T> const* node, int sum) { // strategy: enumerate all root-to-leaf paths (or rather the sum of // the r-t-l paths) and check if (node == nullptr) { return sum == 0; } else { sum -= node->value; return _hasPathSum(node->left, sum) || _hasPathSum(node->right, sum); } }
bool _hasPathSum(TreeNode *root, int sum) { if (!root->left && !root->right && root->val == sum) return true; bool res = false; if (root->left) { res = res || _hasPathSum(root->left, sum - root->val); } if (res) return true; if (root->right) { res = res || _hasPathSum(root->right, sum - root->val); } return res; }
bool hasPathSum(TreeNode *root, int sum) { // Start typing your C/C++ solution below // DO NOT write int main() function if (!root) return false; return _hasPathSum(root, sum); }