#919

Complete Binary Tree Inserter

Medium
TreeBreadth-First SearchDesignBinary TreeBreadth-First SearchQueue
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses a queue to keep track of the nodes at the current level. This allows us to efficiently find the parent node for insertion without traversing the entire tree.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a queue with the root node.
  2. 2Step 2: For each insertion, check the front of the queue to find the parent node.
  3. 3Step 3: Insert the new node as a left or right child of the parent node and update the queue accordingly.
solution.py34 lines
1# Full working Python code
2class TreeNode:
3    def __init__(self, val=0, left=None, right=None):
4        self.val = val
5        self.left = left
6        self.right = right
7
8class CBTInserter:
9    def __init__(self, root: TreeNode):
10        self.root = root
11        self.queue = [root]
12        while self.queue:
13            node = self.queue[0]
14            if node.left:
15                self.queue.append(node.left)
16            if node.right:
17                self.queue.append(node.right)
18            if not node.left or not node.right:
19                break
20            self.queue.pop(0)
21
22    def insert(self, v: int) -> int:
23        new_node = TreeNode(v)
24        parent = self.queue[0]
25        if not parent.left:
26            parent.left = new_node
27        else:
28            parent.right = new_node
29            self.queue.pop(0)
30        self.queue.append(new_node)
31        return parent.val
32
33    def get_root(self) -> TreeNode:
34        return self.root

Complexity note: The time complexity is O(n) for the insert operation due to the queue operations, but since we are not traversing the entire tree for each insertion, it is efficient. The space complexity is O(n) due to the queue storing nodes.

  • 1Using a queue allows efficient tracking of the next insertion point.
  • 2Maintaining the complete binary tree property is crucial for performance.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.