File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed
Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @typedef {Object } TreeNode
3+ * @description Definition for a binary tree node.
4+ * @example
5+ * function TreeNode(val, left, right) {
6+ * this.val = (val===undefined ? 0 : val)
7+ * this.left = (left===undefined ? null : left)
8+ * this.right = (right===undefined ? null : right)
9+ * }
10+ */
11+
12+ /**
13+ * @param {TreeNode } node Node of a binary tree.
14+ * @param {nubmer } lower Inclusive lower bound for the sum.
15+ * @param {nubmer } upper Inclusive upper bound for the sum.
16+ * @param {nubmer } [sum=0] Total sum gathered so far.
17+ * @return {number } Sum between values in the BST.
18+ * @summary Range Sum of BST {@link https://leetcode.com/problems/range-sum-of-bst/}
19+ * @description Given the root node of a binary search tree, return sum between two values (inclusive).
20+ * Space O(h) - Height of the tree.
21+ * Time O(n) - Number of nodes in the tree.
22+ */
23+ const rangeSumBST = ( node , lower , upper , sum = 0 ) => {
24+ if ( node === null ) return 0 ;
25+
26+ if ( node . val >= lower && node . val <= upper ) sum += node . val ;
27+
28+ if ( node . val > lower ) sum += rangeSumBST ( node . left , lower , upper ) ;
29+ if ( node . val < upper ) sum += rangeSumBST ( node . right , lower , upper ) ;
30+
31+ return sum ;
32+ } ;
You can’t perform that action at this time.
0 commit comments