Problem 938
Question statement:
Given the root node of a binary search tree and two integers low and high, return the sum of values of all nodes with a value in the inclusive range [low, high].
Solution
A binary tree is a tree where each node (parent) has at most two associated (sub-)nodes (children). A binary search tree is a data structure where each node has a value (obtained from a poset) and the left child has value $\leq$ than the parent node, and the right child has value $\geq$ the parent node.
Main idea:
Have a sum variable initialized to zero, and whenever we encounter a node satisfying \texttt{low $\leq$ node.val $\leq$ high}$, we add node.val to sum. If on the other hand, $\texttt{node.val $>$ high}, then simply pass to the left sub-tree (and recurse until condition 1 is satisfied). Similarly if $\texttt{node.val $<$ low}$, then simply pass to the right sub-tree (and recurse until condition 1 is satisfied).
Code:
1 | def helper(self, root, low, high, counter): |
Comments:
Time complexity: O(n) where n is the number of nodes in the BST
The above code runs in 123ms beats 87.91% of users. It uses 24.48MB of memory, beating 86.73% of users.