Data Structures · Visualization
Binary Tree: Insert
Binary Tree
In a general (non-search) binary tree, there is no ordering rule for where a new value must go, so insertion typically fills the tree level by level, left to right, to keep it as balanced and compact as possible (like a heap's shape). Time: O(n) (may need to visit every node to find the first open spot). Space: O(n) for the queue in the worst case.
Big-O: Traversals visit every node exactly once: O(n).
Binary Tree: Insert
Binary TreeIn a general (non-search) binary tree, there is no ordering rule for where a new value must go, so insertion typically fills the tree level by level, left to right, to keep it as balanced and compact as possible (like a heap's shape). This is usually done with a breadth-first search to find the first open spot.
How Insert Works
- Start at the root using a queue-based (level-by-level) traversal.
- For each node visited, check if its left child is empty; if so, insert the new node there and stop.
- Otherwise check if its right child is empty; if so, insert the new node there and stop.
- If both children are filled, add both children to the queue and continue to the next node.
Insert Worked Example
Input: Insert 7 into a tree with root 10, left child 5 (right child empty)
- Visit root(10): left child (5) is filled, right child is empty
- Insert 7 as root's right child
Output: 10 / \ 5 7
Press ▶ Run to watch it step by step.
def insert(root, val):
if not root:
return Node(val)
if val < root.val:
root.left = insert(root.left, val)
else:
root.right = insert(root.right, val)
return root
# example: insert 7Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Insert Time & Space Complexity
When to Use Insert
- Building a complete binary tree, such as the shape used by heaps
- Constructing a tree from a level-order list of values
- Any scenario without ordering rules where a balanced shape is desired
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.