pwstrick / daily

一份搜集的前端面试题目清单、面试相关以及各类学习的资料(不局限于前端)
2.38k stars 242 forks source link

二叉搜索树的范围和 #1042

Open pwstrick opened 4 years ago

pwstrick commented 4 years ago

938. 二叉搜索树的范围和

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @param {number} L
 * @param {number} R
 * @return {number}
 */
var sum;
var rangeSumBST = function(root, L, R) {
    sum = 0;
    dfs(root, L, R);
    return sum;
};
function dfs(root, L, R) {
    if(root == null) {
        return;
    }
    if(root.val >= L && root.val <= R) {
        sum += root.val;
    }
    dfs(root.left, L, R);
    dfs(root.right, L, R);
}