Skip to content

Latest commit

 

History

History
40 lines (37 loc) · 1.15 KB

Range Sum of BST.md

File metadata and controls

40 lines (37 loc) · 1.15 KB

Screen Shot 2022-01-17 at 23 21 10

Screen Shot 2022-01-17 at 23 21 18

T.C. DFS O(n)

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @param {number} low
 * @param {number} high
 * @return {number}
 */
var rangeSumBST = function(root, low, high) {
    let ans = 0;
    dfs(root, low, high);
    return ans;
    
    function dfs(root, low, high) {
        if(root) {
            if(low <= root.val && root.val <= high) {
                ans += root.val;
            }
            if(low < root.val) {
                dfs(root.left, low, high);
            }
            if(root.val < high) {
                dfs(root.right, low, high);
            }
        }
    }
};