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 INPUT Initial Tree (root=1) 1 Operations: CBTInserter(root=[1]) insert(2) insert(3) BFS Queue Init: 1 queue stores incomplete nodes Tree: [1], Values: [2, 3] ALGORITHM STEPS 1 Initialize with BFS Queue nodes with <2 children 2 insert(2): Get front node Parent = queue.front() = 1 1 2 Return: 1 3 insert(3): Add right child Parent still = 1 (has 1 child) 1 2 3 Return: 1 4 Pop node 1, add 2 to queue Node 1 now has 2 children FINAL RESULT Complete Binary Tree: 1 2 3 Output Array: [null, 1, 1] CBTInserter: null insert(2): parent = 1 insert(3): parent = 1 OK - Tree Complete! Key Insight: Use BFS to maintain a queue of nodes that can accept children. The front of the queue is always the next parent for insertion. When a node gets 2 children, pop it from queue. This ensures O(1) insertion while maintaining the complete binary tree property (all levels filled left to right). TutorialsPoint - Complete Binary Tree Inserter | BFS Approach
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