Leetcode 919: Complete Binary Tree Inserter

grid47
grid47
Exploring patterns and algorithms
Aug 7, 2024 7 min read

You are given a complete binary tree. A complete binary tree is one where every level, except possibly the last, is completely filled, and all nodes are as far left as possible. Your task is to design a data structure that supports inserting new nodes while maintaining the completeness of the binary tree. Implement the CBTInserter class that supports two operations: inserting a new node and returning the root of the tree.
Problem
Approach
Steps
Complexity
Input: You are given the root of a complete binary tree and a value to insert.
Example: Input: root = [1, 2], val = 3
Constraints:
• 1 <= n <= 1000
• 0 <= Node.val <= 5000
• 0 <= val <= 5000
• At most 10^4 calls to insert and get_root will be made.
Output: The `insert` method should return the value of the parent node of the newly inserted node. The `get_root` method should return the root node of the tree.
Example: Output: [null, 1, 2, [1, 2, 3, 4]]
Constraints:
• The tree will always remain complete after each insertion.
Goal: The goal is to maintain the completeness of the binary tree after each insertion while ensuring efficient updates.
Steps:
• Use a list (array) to store the nodes in level-order. This allows easy access to parent and child nodes for insertion.
• When inserting a new node, add it to the list and determine whether it should be the left or right child of its parent, based on the index of the new node.
• Update the tree structure in the list and return the parent node's value.
Goal: The tree will contain at least one node, and the values will be within the specified ranges.
Steps:
• The tree will contain between 1 and 1000 nodes.
• Each node's value and the value to be inserted will be between 0 and 5000.
• At most 10^4 operations will be performed.
Assumptions:
• The input binary tree is a complete binary tree before the first insertion.
• The new node will always be inserted in the next available spot in the tree to maintain completeness.
Input: Input: root = [1, 2], val = 3
Explanation: The tree before insertion is [1, 2]. After inserting 3, the new tree becomes [1, 2, 3], where 1 is the parent of 2 and 3. The return value is the parent node's value, which is 1.

Input: Input: root = [1, 2, 3, 4], val = 5
Explanation: Before the insertion, the tree is [1, 2, 3, 4]. After inserting 5, the tree becomes [1, 2, 3, 4, 5]. The parent node of 5 is 2, so the return value is 2.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus