Insert into a Left-Complete Binary Tree
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) → TreeNodeExamples
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
rootcontains between0and8191nodes.- All node values and
valueare integers between-10^4and10^4. rootis a complete binary tree. Its level-order representation contains no null entries.