--- tags: leetcode --- # [112. Path Sum](https://leetcode.com/problems/path-sum/) --- # My Solution ## The Key Idea for Solving This Coding Question ## C++ Code ```cpp= /** * 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) {} * }; */ class Solution { public: bool hasPathSum(TreeNode *root, int targetSum) { if (root == nullptr) { return false; } if (root->left == nullptr && root->right == nullptr && root->val == targetSum) { return true; } return hasPathSum(root->left, targetSum - root->val) || hasPathSum(root->right, targetSum - root->val); } }; ``` ## Time Complexity $O(n)$ $n$ is the number of nodes in the binary tree referred by `root`. ## Space Complexity $O(H)$ $H$ is the height of the binary tree referred by `root`. # Miscellane <!-- # Test Cases ``` [5,4,8,11,null,13,4,7,2,null,null,null,1] 22 ``` ``` [1,2,3] 5 ``` ``` [] 0 ``` ``` [1,2] 1 ``` ``` [1] 1 ``` ``` [-2,6,null,0,-6] 4 ``` * Wrong Answer ``` [1,2] 1 ``` -->