「每日LeetCode」2022年7月25日

本文最后更新于:2023年3月19日 晚上

919.完全二叉树插入器

919.完全二叉树插入器

Category Difficulty Likes Dislikes
algorithms Medium (65.86%) 117 -

Tags
Companies
完全二叉树 是每一层(除最后一层外)都是完全填充(即,节点数达到最大)的,并且所有的节点都尽可能地集中在左侧。
设计一种算法,将一个新节点插入到一个完整的二叉树中,并在插入后保持其完整。
实现 CBTInserter 类:

  • CBTInserter(TreeNode root) 使用头节点为 root 的给定树初始化该数据结构;
  • CBTInserter.insert(int v) 向树中插入一个值为 Node.val == val 的新节点 TreeNode。使树保持完全二叉树的状态,并返回插入节点 TreeNode 的父节点的值
  • CBTInserter.get_root() 将返回树的头节点。

示例 1:

输入 [“CBTInserter”, “insert”, “insert”, “get_root”] [[[1, 2]], [3], [4], []] 输出 [null, 1, 2, [1, 2, 3, 4]] 解释 CBTInserter cBTInserter = new CBTInserter([1, 2]); cBTInserter.insert(3); // 返回 1 cBTInserter.insert(4); // 返回 2 cBTInserter.get_root(); // 返回 [1, 2, 3, 4]

提示:

  • 树中节点数量范围为 [1, 1000]
  • 0 <= Node.val <= 5000
  • root 是完全二叉树
  • 0 <= val <= 5000
  • 每个测试用例最多调用 insert 和 get_root 操作 104 次

Discussion | Solution

思路

层次遍历,找到第一个空的节点,将目标节点插入其左孩子节点或者右孩子节点

解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
* @lc app=leetcode.cn id=919 lang=javascript
*
* [919] 完全二叉树插入器
*/

// @lc code=start
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
*/
var CBTInserter = function (root) {
this.root = root;
};

/**
* @param {number} val
* @return {number}
*/
CBTInserter.prototype.insert = function (val) {
let queue = [this.root];
while (queue.length) {
const row = queue.slice();
const temp = [];

while (row.length) {
const node = row.shift();

if (!node.left) {
node.left = new TreeNode(val);
return node.val;
} else if (!node.right) {
node.right = new TreeNode(val);
return node.val;
}

if (node.left) temp.push(node.left);
if (node.right) temp.push(node.right);
}

queue = temp;
}
};

/**
* @return {TreeNode}
*/
CBTInserter.prototype.get_root = function () {
return this.root;
};

/**
* Your CBTInserter object will be instantiated and called as such:
* var obj = new CBTInserter(root)
* var param_1 = obj.insert(val)
* var param_2 = obj.get_root()
*/
// @lc code=end