Talentd
FleetCode

919. Complete Binary Tree Inserter

Medium65.0% acceptance3 companies

A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible.

Design an algorithm to insert a new node to a complete binary tree keeping it complete after the insertion.

Implement the CBTInserter class:

  • CBTInserter(TreeNode root) Initializes the data structure with the root of the complete binary tree.
  • int insert(int v) Inserts a TreeNode into the tree with value Node.val == val so that the tree remains complete, and returns the value of the parent of the inserted TreeNode.
  • TreeNode get_root() Returns the root node of the tree.

Example 1:

Input
["CBTInserter", "insert", "insert", "get_root"]
[[[1, 2]], [3], [4], []]
Output
[null, 1, 2, [1, 2, 3, 4]]

Explanation
CBTInserter cBTInserter = new CBTInserter([1, 2]);
cBTInserter.insert(3);  // return 1
cBTInserter.insert(4);  // return 2
cBTInserter.get_root(); // return [1, 2, 3, 4]

Constraints:

  • The number of nodes in the tree will be in the range [1, 1000].
  • 0 <= Node.val <= 5000
  • root is a complete binary tree.
  • 0 <= val <= 5000
  • At most 104 calls will be made to insert and get_root.

Asked at 3 companies

21:59
Still stuck?Read 3 approaches, or watch a walkthrough.
Open solution
Loading editor…
1# Definition for a binary tree node.
2# class TreeNode:
3# def __init__(self, val=0, left=None, right=None):
4# self.val = val
5# self.left = left
6# self.right = right
7class CBTInserter:
8
9 def __init__(self, root: Optional[TreeNode]):
10
11
12 def insert(self, val: int) -> int:
13
14
15 def get_root(self) -> Optional[TreeNode]:
16
17
18
19# Your CBTInserter object will be instantiated and called as such:
20# obj = CBTInserter(root)
21# param_1 = obj.insert(val)
22# param_2 = obj.get_root()
Starter codePython 3Spaces: 4
Examples
Input
["CBTInserter","insert","insert","get_root"]
[[[1,2]],[3],[4],[]]
Your code is saved on this device.Solution