算法小白,2024年2月21日,开始挑战在掘金发布“每日”系列。 (节假日可能会出门所以不算) 涉及到算法,type challenge 等,感兴趣的小伙伴可以持续关注督促互勉 🚀🚀🚀
算法
题意理解
给定二叉搜索树的根结点 root,返回值位于范围 [low, high] 之间的所有结点的值的和
思路
- 遍历二叉树
- 对比值是否在区间范围内
- 返回和
解题
const rangeSumBST = (root, low, high) => {
let sum = 0
const queue = [root]
while (queue.length) {
let size = queue.length
for (let i = 0; i < size; i++) {
let node = queue.pop()
if ((node?.val >= low) && (node?.val <= high)) {
sum += node.val
}
node?.left && queue.push(node.left)
node?.right && queue.push(node.right)
}
}
return sum
}
优化
使用二叉搜索树的性质,可以对解法进行优化。左子树的所有节点值比当前节点小,右子树所有节点的值比当前节点大
如果当前节点值比 high 大,我们只需要遍历左侧节点即可。对于 low 也一样
const rangeSumBST = (root, low, high) => {
if (!root) return 0
if (root.val > high) return rangeSumBST(root.left, low, high)
if (root.val < low) return rangeSumBST(root.right, low, high)
return root.val + rangeSumBST(root.left, low, high) + rangeSumBST(root.right, low, high)
}
TypeChallenge
实现类型 Absolute<T> ,接收一个 number | string | bigint ,返回正整数字符串
type todo = -100
type preview = Absolute<todo> // 100
思路
- 将输入类型转换成字符串类型
- 通过模板字符串和类型推导去除负号
- 返回剩余部分
type Absolute<T extends number | string | bigint> = `${T}` extends `-${infer U}`
? U
: `${T}`