From 30202920b00ed5689c312e81e02f26849ca3202e Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Mon, 8 Jan 2024 11:50:46 +0100 Subject: [PATCH] =?UTF-8?q?cpp:=20add=20=E2=80=9C938.=20Range=20Sum=20of?= =?UTF-8?q?=20BST=E2=80=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- cpp/range-sum-of-bst.cpp | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 cpp/range-sum-of-bst.cpp diff --git a/cpp/range-sum-of-bst.cpp b/cpp/range-sum-of-bst.cpp new file mode 100644 index 0000000..39505e3 --- /dev/null +++ b/cpp/range-sum-of-bst.cpp @@ -0,0 +1,28 @@ +/** + * 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: + int rangeSumBST(TreeNode *root, int low, int high) { + if (root == nullptr) { + return 0; + } + + int currentValue = 0; + if (low <= root->val && root->val <= high) { + currentValue = root->val; + } + + return (currentValue + rangeSumBST(root->left, low, high) + + rangeSumBST(root->right, low, high)); + } +};