Complete Binary Tree Inserter - 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 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.

Input & Output

Example 1 — Basic Operations
$ Input: operations = ["CBTInserter", "insert", "insert"], values = [[1], [2], [3]]
Output: [null, 1, 1]
💡 Note: Initialize with tree [1]. Insert 2 as left child of 1 (return 1). Insert 3 as right child of 1 (return 1).
Example 2 — Multi-level Tree
$ Input: operations = ["CBTInserter", "insert", "insert", "insert"], values = [[1, 2], [3], [4], [5]]
Output: [null, 1, 2, 2]
💡 Note: Start with [1,2]. Insert 3 as right child of 1. Insert 4 as left child of 2. Insert 5 as right child of 2.
Example 3 — Complete Tree Growth
$ Input: operations = ["CBTInserter", "insert", "insert", "get_root"], values = [[1, 2, 3, 4], [5], [6], []]
Output: [null, 2, 2, [tree]]
💡 Note: Tree [1,2,3,4]. Insert 5 as right child of 2. Insert 6 as left child of 3. Tree grows level by level.

Constraints

  • 1 ≤ operations.length ≤ 1000
  • 1 ≤ val ≤ 100
  • The given tree is always a complete binary tree

Visualization

Tap to expand
Complete Binary Tree Inserter OverviewInitial Tree12Insert ProcessAdd nodes level by level, left to rightinsert(3)insert(4)Result Tree1234Complete property maintained: all levels filled left to rightReturns parent value for each insertionEfficient O(1) insertion using candidate queue optimization
Understanding the Visualization
1
Input Tree
Initial complete binary tree with some nodes
2
Insert Process
Add nodes level by level, left to right
3
Complete Tree
Resulting tree maintains complete property
Key Takeaway
🎯 Key Insight: Pre-maintain a queue of nodes with available children for O(1) insertions
Asked in
Google 25 Amazon 18 Microsoft 15 Facebook 12
28.5K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen