Skip to main content
LeetCode 919, Medium. Topics: Tree, Breadth-First Search, Design, Binary Tree. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 18 parametrized pytest cases, and a playground notebook:

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

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, full suite in test_solution.py:

Complexity

Tags

Last modified on September 7, 2026