/** * @param {TreeNode} root * @param {number} low * @param {number} high * @return {number} */var rangeSumBST = function (root, low, high) { let sum = 0 // 缓存结点值之和 let queue = [root] // 使用队列进行BFS搜索,初始值为树的根节点
// 当队列被清空,表示搜索结束 while (queue.length) { // 缓存当前一层的节点数量 let queueLength = queue.length
// 将当前一层的节点清空 while (--queueLength >= 0) { // 从队列中取出当前层的一个节点 const node = queue.shift()
// 如果节点为空,则跳过 if (!node) { continue }
// 当前节点的值小于low,它左侧的值都小于low,因此只要查找右侧节点 if (node.val < low) { queue.push(node.right) } // 当前节点的值大于high,它左侧的值都大于high,因此只要查找右侧节点 else if (node.val > high) { queue.push(node.left) } else { // 如果当前节点的值在[low, high]之间,就将其与子树的值加到sum sum += node.val // 继续向其子树搜索 queue.push(node.left) queue.push(node.right) } } }
return sum}
评论