✅ Beats 100% ⚡ |  Simple DFS 💡|  7 lines only 😉
\n\n# Intuition\n Describe your first thoughts on how to solve this problem. \n All we need is to visit each node, and if it falls in the specified range, incre
![image.png](https://assets.leetcode.com/users/images/9abe8bf5-f988-43d0-80b9-89fd002e87ea_1704672742.3120453.png)\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n* All we need is to visit each node, and if it falls in the specified range, increment its value with us. \n# Approach\n<!-- Describe your approach to solving the problem. -->\n* This solution is recursive solution\n## Base case\n* if ! root means that we are a child of a leaf node, so just return 0. \n\n## Recursive case\n1. get the value of the left child, by applying recursive call and send the root as the left child.\n2. get the value of the right child, by applying recursive call and send the root as the right child.\n3. if the current value was in the given range inclusive \n    1. return the sum of left, right and the current\n4. else \n    1. return the sum of left and right children only.\n   \n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n1. O(n) -> the number of nodes.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n1. no auxilary space is needed, but since it is recursive, so it may take O(d) where d is the maximum depth.\n# Code\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode() : val(0), left(nullptr), right(nullptr) {}\n *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\n #pragma GCC optimize("O3")\n#pragma GCC optimize("Ofast", "inline", "ffast-math", "unroll-loops", "no-stack-protector")\n#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native", "f16c")\nstatic const auto DPSolver = []()\n{ std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); return \'c\'; }();\nclass Solution {\npublic:\n    Solution(){\n        DPSolver;\n    }\n    int rangeSumBST(TreeNode *root, int low, int high)\n    {\n        \n        // base cases\n        if (!root)\n            return 0;\n\n        int right = rangeSumBST(root->right, low,high); \n        int left = rangeSumBST(root->left, low,high); \n        if (root->val >= low && root->val <= high )\n            return right + left + root->val;\n        return right + left ;\n    }\n};\n```
['Tree', 'Depth-First Search', 'Binary Search Tree', 'Recursion', 'Binary Tree', 'C++']