Complete Binary Tree Inserter — LeetCode 919 Python Solution
- Problem
- #919
- Pattern
- Tree Traversal
- Reading time
- 7 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- ["CBTInserter", "insert", "insert", "get_root"]
- Output
- [null, 1, 2, [1, 2, 3, 4]]
- Explanation
- CBTInserter cBTInserter = new CBTInserter([1, 2]);
Python solution
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class CBTInserter:
def __init__(self, root: Optional[TreeNode]):
self.tree = []
q = deque([root])
while q:
for _ in range(len(q)):
node = q.popleft()
self.tree.append(node)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
def insert(self, val: int) -> int:
p = self.tree[(len(self.tree) - 1) // 2]
node = TreeNode(val)
self.tree.append(node)
if p.left is None:
p.left = node
else:
p.right = node
return p.val
def get_root(self) -> Optional[TreeNode]:
return self.tree[0]
# Your CBTInserter object will be instantiated and called as such:
# obj = CBTInserter(root)
# param_1 = obj.insert(val)
# param_2 = obj.get_root()Complexity
| Measure | Complexity |
|---|---|
| Time | O(V+E) |
| Space | O(n), where n is the number of nodes in the tree auxiliary |
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 919. Complete Binary Tree Inserter is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.
The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 919. Complete Binary Tree Inserter?
- LeetCode 919. Complete Binary Tree Inserter is rated Medium on LeetCode.
- What is the time complexity of LeetCode 919. Complete Binary Tree Inserter?
- The Python solution on this page runs in O(V+E).
- What is the space complexity of LeetCode 919. Complete Binary Tree Inserter?
- The Python solution on this page uses O(n), where n is the number of nodes in the tree auxiliary space.
- What topics does LeetCode 919. Complete Binary Tree Inserter cover?
- LeetCode 919. Complete Binary Tree Inserter is tagged Tree, Breadth-First Search, Design and Binary Tree on LeetCode.