#919
Complete Binary Tree Inserter
specialist · 640 · lc medium +30 · 65% accepted · 1,154 likes · top 69%
Description
A complete binary tree has every level fully filled except possibly the last, where nodes are packed as far left as possible. Implement CBTInserter to support efficient insertion while preserving completeness:
- CBTInserter(TreeNode root) initializes with an existing complete binary tree.
- int insert(int val) adds a new node with value val and returns the value of its parent.
- TreeNode get_root() returns the current root of the tree.
Example 1:
Input
["CBTInserter", "insert", "insert", "get_root"]
[[[1, 2]], [3], [4], []]
Output
[null, 1, 2, [1, 2, 3, 4]]
Example 2:
Explanation
CBTInserter cBTInserter = new CBTInserter([1, 2]);
cBTInserter.insert(3); // return 1
cBTInserter.insert(4); // return 2
cBTInserter.get_root(); // return [1, 2, 3, 4]
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22