# 112. Path Sum Difficulty: Easy ## Solution ```cpp= /** *** Author: R-CO *** E-mail: daniel1820kobe@gmail.com *** Date: 2020-11-11 **/ #include <cstdlib> #include <iostream> using std::cout; using std::endl; struct TestCasesStruct {}; /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), * right(right) {} * }; */ struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode() : val(0), left(nullptr), right(nullptr) {} TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} }; class Solution { public: bool hasPathSum(TreeNode* root, int sum) { bool result = false; preorderTraversal(root, sum, result); return result; } private: void preorderTraversal(TreeNode *node, int sum, bool &result) { if (node == nullptr) { return; } sum -= node->val; if (sum == 0 && node->left == nullptr && node->right == nullptr) { result = true; return; } preorderTraversal(node->left, sum, result); preorderTraversal(node->right, sum, result); } }; int main(int argc, char *argv[]) { return EXIT_SUCCESS; } ``` ## Result Success Details Runtime: 4 ms, faster than 99.93% of C++ online submissions for Path Sum. Memory Usage: 21.7 MB, less than 72.97% of C++ online submissions for Path Sum. ###### tags: `LeetCode-Easy` `C++`