FastPrepInsert into a Left-Complete Binary Tree

Insert into a Left-Complete Binary Tree

Rubrik logoRubrik● MediumFULLTIMEONSITE INTERVIEW

Problem statement

Insert a new node with value value into the binary tree root while keeping the tree complete.

A complete binary tree has every level full except possibly the last, and the last level is filled from left to right. Insert the new node at the first empty position in level order, keeping every existing node and value in place. An empty tree becomes a single-node tree. Duplicate values are allowed.

Return the resulting root. Use the provided TreeNode type and implement the tree logic yourself without a tree-library insertion routine.

A linear breadth-first search is a useful starting point. Then use the complete-tree structure to find the insertion position in less than linear time. Analyze the insertion work separately from reading or serializing the whole tree.

Function

insertComplete(root: TreeNode, value: int) → TreeNode

Examples

Example 1

root = [1,2,3,4,5]value = 6return = [1,2,3,4,5,6]

The first empty position is the left child of the node with value 3. Adding 6 there preserves left-to-right filling of the last level.

Example 2

root = [4,7,9]value = 2return = [4,7,9,2]

The first two levels are full. The new level starts with the left child of the node with value 7.

Constraints

  • root contains between 0 and 8191 nodes.
  • All node values and value are integers between -10^4 and 10^4.
  • root is a complete binary tree. Its level-order representation contains no null entries.

More Rubrik problems

See Rubrik hiring insights
Saved
public TreeNode insertComplete(TreeNode root, int value) {
    // write your code here
}
Checking account…