# [Leetcode 112] Path Sum

`/** * 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) {        //code section}`
` int restSum; if(root == nullptr)     return false; else     restSum = targetSum — root->val; if(root->left == nullptr && root->right == nullptr) {     if(restSum == 0)         return true;     else         return false; } else     return hasPathSum(root->left, restSum) || hasPathSum(root->right, restSum);`
`// preorderif(root == nullptr)    return false;std::vector<TreeNode*> stack;std::map<TreeNode*, int> done;stack.push_back(root);while(!stack.empty()){    TreeNode* node = stack.back();    if(done.count(node) != 0)    {        targetSum += node->val;        stack.pop_back();    }    else    {        targetSum -= node->val;    }                if(node->left == nullptr && node->right == nullptr)    {        if(targetSum == 0)            return true;        targetSum += node->val;        stack.pop_back();    }    //traverse    if(done.count(node) == 0)    {        if(node->right != nullptr)        {            stack.push_back(node->right);            done[node]++;        }        if(node->left != nullptr)        {            stack.push_back(node->left);            done[node]++;        }    }}return false;`

--

--

--

## More from Samuel Liu

Hi I am Samuel

Love podcasts or audiobooks? Learn on the go with our new app.

Hi I am Samuel