zentan66 / daily-coding

日常手写算法,编程题
0 stars 0 forks source link

LeetCode-二叉搜索树的范围和 #22

Open zentan66 opened 3 years ago

zentan66 commented 3 years ago

给定二叉搜索树的根结点 root,返回值位于范围 [low, high] 之间的所有结点的值的和。

其实就是按照中序排列,然后将[low,high]之间的数值累加

zentan66 commented 3 years ago

编码

/**
 * @param {TreeNode} root
 * @param {number} low
 * @param {number} high
 * @return {number}
 */
var rangeSumBST = function (root, low, high) {
  let result = 0
  function dfs(p) {
    if (!p) return
    dfs(p.left)
    if (p.val >= low && p.val <= high) {
      result += p.val
    }
    dfs(p.right)
  }
  dfs(root)
  return result
}