
In the context of binary trees, a complete binary tree is defined as one in which every level—except possibly the last—is completely filled, and all nodes are as far left as possible.
Your task is to design a class CBTInserter that:
The operations to implement include:
CBTInserter(TreeNode root) – Initializes the data structure with the given root.int insert(int val) – Inserts a new node with value val in a way that maintains tree completeness. Returns the value of the parent node to which the new node was added.TreeNode get_root() – Returns the root node of the tree after all insertions.Input:
Output:
Explanation:
CBTInserter cBTInserter = new CBTInserter([1, 2]);
Initializes the tree with root 1 and left child 2.
cBTInserter.insert(3); ➜ returns 1
Adds 3 as the right child of node 1.
cBTInserter.insert(4); ➜ returns 2
Adds 4 as the left child of node 2.
cBTInserter.get_root(); ➜ returns [1, 2, 3, 4]
Returns the updated tree in level order.
[1, 1000].0 <= Node.val <= 50000 <= val <= 5000root is a complete binary tree.10⁴ calls will be made to insert and get_root.Maintaining completeness during insertions requires identifying the next available position in level order (left to right, top to bottom). A queue makes this efficient.
Track Incomplete Nodes:
Insert Operation:
Get Root Operation:
[1, 2]. Node 1 has left child 2.3: Node 1 gets 3 as right child. Now both its children are filled, so it's removed from the queue.4: Node 2 gets 4 as left child.[1, 2, 3, 4].This method leverages BFS and a queue to ensure that insertions always respect the structure of a complete binary tree.
This solution implements a class named CompleteBinaryTreeInserter for managing the insertion of nodes into a complete binary tree in Java. The class uses a TreeNode for the tree structure and maintains the nodes in a level-order fashion using Java's Deque and Queue interfaces.
Initialize an instance with an existing root node. During initialization, the constructor leverages breadth-first search (BFS) to populate a Deque (nodeDeque), helping to track where the next child node will be inserted. Nodes that may still accept new children (nodes missing either left or right child) are added to nodeDeque.
The insert method adds a new node with a specified value into the tree. It retrieves the first node in nodeDeque that requires a new child and attaches the new node appropriately as either a left or right child. If a node receives a new right child, it's deemed complete and removed from nodeDeque. The value of the parent node is returned after the insertion.
The getRoot method simply returns the root of the current tree.
This structure ensures efficient node insertions while maintaining the complete binary tree characteristics: each level of the tree is filled entirely before moving on to a new level, and each new node is inserted at the leftmost available position at the bottom level.
0 Comments
Be the first to comment and share your perspective with the community.