更新时间:2023-02-26 20:38:58
将你的链表扁平化成数组后,你可以使用 Array.prototype.reduce()
带有一个 min 和
max
,分别从 Infinity
和 -Infinity
的初始值开始,以匹配 Math.min()
和 Math.max()
:
After flattening your linked list into an array, you can use Array.prototype.reduce()
with an accumulator that is a tuple of min
and max
, starting with initial values of Infinity
and -Infinity
respectively to match the implementations of Math.min()
and Math.max()
:
const object = {
value: 1,
children: {
value: 10,
children: {
value: 2,
children: {
value: 5,
children: null
}
}
}
}
const flat = o => o == null || o.value == null ? [] : [o.value, ...flat(o.children)]
const [min, max] = flat(object).reduce(
([min, max], value) => [Math.min(min, value), Math.max(max, value)],
[Infinity, -Infinity]
)
console.log(min, max)