天津市住房和城乡建设厅官方网站,做网站时搜索的代码是什么,海南省建设公司官网,wordpress精致主题原题链接#xff1a; https://leetcode.cn/problems/range-sum-of-bst/
解题思路#xff1a;
对于二叉搜索树的任意节点#xff0c;左子树的所有节点值都小于它的值#xff0c;右子树的所有节点值都小于它的值。使用队列进行BFS搜索#xff0c;如果当前节点的值小于low https://leetcode.cn/problems/range-sum-of-bst/
解题思路
对于二叉搜索树的任意节点左子树的所有节点值都小于它的值右子树的所有节点值都小于它的值。使用队列进行BFS搜索如果当前节点的值小于low只要向右子树搜索。如果当前节点的值大于high只要向左子树搜索。如果当前节点的值在[low, high]之间就将其与子树的值相加返回
/*** 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]之间就将其与子树的值加到sumsum node.val// 继续向其子树搜索queue.push(node.left)queue.push(node.right)}}}return sum
}