> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Complete Binary Tree Inserter Python Solution

> Tested Python solution for LeetCode 919 with 18 pytest cases. Generate a practice environment with lcpy.

LeetCode 919, [Medium](/catalog/medium). Topics: [Tree](/catalog/topics/tree), [Breadth-First Search](/catalog/topics/breadth-first-search), [Design](/catalog/topics/design), [Binary Tree](/catalog/topics/binary-tree). [View on LeetCode](https://leetcode.com/problems/complete-binary-tree-inserter/description/).

Generate this problem as a practice environment: tested reference solution, 18 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 919   # by problem number
lcpy gen -s complete_binary_tree_inserter   # by problem name
```

## Problem

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 val)` 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.

### Examples

![Example 1](https://assets.leetcode.com/uploads/2021/08/03/lc-treeinsert.jpg)

```
Input
["CBTInserter", "insert", "insert", "get_root"]
[[[1, 2]], [3], [4], []]
Output
[null, 1, 2, [1, 2, 3, 4]]

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]
```

### Constraints

* The number of nodes in the tree will be in the range `[1, 1000]`.
* `0 <= Node.val <= 5000`
* `root` is a complete binary tree.
* `0 <= val <= 5000`
* At most `10^4` calls will be made to `insert` and `get_root`.

**Follow up:** Can you implement `insert` in `O(1)` time per call, using the structure of a complete binary tree?

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/complete_binary_tree_inserter/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/complete_binary_tree_inserter/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from collections import deque

from leetcode_py import TreeNode


class CBTInserter:
    # Time: __init__ O(n), insert O(1), get_root O(1)
    # Space: O(n)
    def __init__(self, root: TreeNode[int] | None) -> None:
        self.root = root
        self.candidates: deque[TreeNode[int]] = deque()
        if root is None:
            return
        queue: deque[TreeNode[int]] = deque([root])
        while queue:
            node = queue.popleft()
            if node.left is None or node.right is None:
                self.candidates.append(node)
            if node.left is not None:
                queue.append(node.left)
            if node.right is not None:
                queue.append(node.right)

    def insert(self, val: int) -> int:
        parent = self.candidates[0]
        node: TreeNode[int] = TreeNode(val)
        if parent.left is None:
            parent.left = node
        else:
            parent.right = node
            self.candidates.popleft()
        self.candidates.append(node)
        return parent.val

    def get_root(self) -> TreeNode[int] | None:
        return self.root
```

## Complexity

| Time | Space |
| - | - |
| **init** O(n), insert O(1), get\_root O(1) | O(n) |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.