[LeetCode] Complete Binary Tree Inserter

919. Complete Binary Tree Inserter

A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible.

Design an algorithm to insert a new node to a complete binary tree keeping it complete after the insertion.

Implement the CBTInserter class:

  • CBTInserter(TreeNode root) Initializes the data structure with the root of the complete binary tree.
  • int insert(int v) Inserts a TreeNode into the tree with value Node.val == val so that the tree remains complete, and returns the value of the parent of the inserted TreeNode.
  • TreeNode get_root() Returns the root node of the tree.
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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class CBTInserter {
TreeNode* dummy;
int mask = 1;
int getFrontMask() { //o(log(n))
int fMask = 1;

while(fMask <= mask) fMask<<=1;

return fMask>>1;
}
int traverse(int fMask, TreeNode* node, int& val) { //o(log(n))
if(fMask == 1) {
if(mask & fMask) node->right = new TreeNode(val);
else node->left = new TreeNode(val);
return node->val;
}

if(mask & fMask) return traverse(fMask>>1, node->right, val);
else return traverse(fMask>>1, node->left, val);
}
public:
CBTInserter(TreeNode* root) { //o(n)
dummy = new TreeNode(-1, nullptr, root);
queue<TreeNode*> q;
if(root) q.push(root);
while(!q.empty()) {
mask++;
auto node = q.front(); q.pop();
if(node->left) q.push(node->left);
if(node->right) q.push(node->right);
}
}

int insert(int val) { //o(log(n))
int fMask = getFrontMask();
int res = traverse(fMask, dummy, val);
mask++;
return res;
}

TreeNode* get_root() { //o(1)
return dummy->right;
}
};

/**
* Your CBTInserter object will be instantiated and called as such:
* CBTInserter* obj = new CBTInserter(root);
* int param_1 = obj->insert(val);
* TreeNode* param_2 = obj->get_root();
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/26/PS/LeetCode/complete-binary-tree-inserter/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.