Time Complexity of Binary Tree Operations


Binary trees are hierarchical structures that provide flexible and powerful ways to organize data. The performance of common operations in a binary tree—such as insertion, deletion, traversal, and search—depends on the shape of the tree. In a balanced binary tree, most operations take logarithmic time. However, in the worst case, performance may degrade to linear time.

Summary Table

Operation Best Case Average Case Worst Case
Insertion O(1) O(log N) O(N)
Deletion O(log N) O(log N) O(N)
Traversal O(N) O(N) O(N)
Search O(1) O(log N) O(N)
Height O(log N) O(log N) O(N)
Count Nodes O(N) O(N) O(N)
Count Leaf Nodes O(N) O(N) O(N)
Mirror / Invert O(N) O(N) O(N)

1. Insertion

Inserting a node in a binary tree can be done level-wise (in a complete binary tree) or by rules (in a BST). In general binary trees, you may insert at the first vacant position using BFS.

2. Deletion

Deleting a node in a binary tree involves three scenarios: deleting a leaf, a node with one child, or a node with two children. In general trees, deletion may involve swapping with the deepest node.

3. Traversal

Traversal involves visiting every node in the tree. Types include in-order, pre-order, post-order, and level-order.

Searching involves checking whether a value exists in the tree.

5. Height Calculation

The height of a binary tree is the number of nodes on the longest path from root to a leaf.

6. Count Total Nodes

To count all nodes, each node must be visited.

7. Count Leaf Nodes

Leaf nodes are those with no children. You must visit each node to check if it’s a leaf.

8. Mirror / Invert Tree

Mirroring a binary tree means swapping left and right children recursively for all nodes.