Skip to content

Practice Complete Binary Tree Inserter

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Medium#919
LeetCode Problem

Complete Binary Tree Inserter

Problem Statement

CBTInserter(root) receives a nonempty complete binary tree: every level except possibly the last is full, and the last is filled left to right. insert(val) adds a node while preserving completeness and returns its parent value. get_root() returns the tree root. Practice approach: Breadth-first initialize a queue of nodes missing at least one child. Insert under the queue head, filling left before right; remove a parent once full and append the new node. Initialization is O(n), and later insertions are O(1). The example represents trees in level order.

Source: Complete Binary Tree Inserter on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
["CBTInserter","insert","insert","get_root"]
[[[4,7,9]],[2],[6],[]]
Output
[null,7,7,[4,7,9,2,6]]
Explanation

Both inserted nodes become children of 7, filling the next available positions from left to right.

Constraints

Initial tree contains 1 to 1000 nodes and is complete.
0 <= Node.val, val <= 5000
At most 10^4 total calls.

Related LeetCode Problems

Practice more problems similar to Complete Binary Tree Inserter.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.