持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第9天,点击查看活动详情
每日刷题 2022.10.07
- leetcode原题链接:leetcode.cn/problems/Kn…
- 难度:中等
题目
- 力扣嘉年华上的 DIY 手工展位准备了一棵缩小版的 二叉 装饰树 root 和灯饰,你需要将灯饰逐 一插入装饰树中,要求如下:
- 完成装饰的二叉树根结点与 root 的根结点值相同
- 若一个节点拥有父节点,则在该节点和他的父节点之间插入一个灯饰(即插入一个值为 -1 的节点)。具体地:
- 在一个 父节点 x 与其左子节点 y 之间添加 -1 节点, 节点 -1、节点 y 为各自父节点的左子节点,
- 在一个 父节点 x 与其右子节点 y 之间添加 -1 节点, 节点 -1、节点 y 为各自父节点的右子节点,
- 现给定二叉树的根节点 root ,请返回完成装饰后的树的根节点
示例
- 示例1
输入:
`root = [7,5,6]`
输出:`[7,-1,-1,5,null,null,6]`
解释:如下图所示
- 示例2
输入:
root = [3,1,7,3,8,null,4]
输出:[3,-1,-1,1,null,null,7,-1,-1,null,-1,3,null,null,8,null,4]
解释:如下图所示
提示
0 <= root.Val <= 1000
root
节点数量范围为[1, 10^5]
解题思路
- 根据题意分析:对树中的每一个节点(除叶子节点之外)后面都要添加一个
-1
- 主要的操作步骤(使用递归的调用:每一个节点)
- 起始时根节点进入队列,然后每次从队列中选出一个节点。
- 如果当前节点有左子树,则在中间插入一个节点,然后左子树进入队列。
- 如果当前节点右右子树,则在中间插入一个节点,然后右子树进入队列。
- 队列元素全部遍历完毕,返回根节点
AC
代码
var StockPrice = function() {
this.map = new Map();
this.obj = {
time: -1,
price: -1
};
// 可以整体排序,避免每一次都需要排序
this.maxQueue = new MaxPriorityQueue({
compare: (e1,e2) => e2.price - e1.price
});
this.minQueue = new MinPriorityQueue({
compare: (e1,e2) => e1.price - e2.price
});
};
StockPrice.prototype.update = function(timestamp, price) {
this.map.set(timestamp, price);
this.maxQueue.enqueue({
time: timestamp,
price: price
});
this.minQueue.enqueue({
time: timestamp,
price: price
});
if(this.obj.time <= timestamp) {
this.obj.price = price
this.obj.time = timestamp
}
};
/**
* @return {number}
*/
StockPrice.prototype.current = function() {
return this.obj.price;
};
/**
* @return {number}
*/
StockPrice.prototype.maximum = function() {
// 判断当前的是否是正确的
while(true) {
let cur = this.maxQueue.front(), t = this.map.get(cur.time);
if(cur.price === t) {
return cur.price;
}else this.maxQueue.dequeue();
}
};
/**
* @return {number}
*/
StockPrice.prototype.minimum = function() {
while(true) {
let cur = this.minQueue.front(), t = this.map.get(cur.time);
if(cur.price === t) {
return cur.price;
}else this.minQueue.dequeue();
}
};