binary tree
balanced tree
data structures
algorithm
tree traversal

How to determine if binary tree is balanced?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

A balanced binary tree is a tree in which the height of the two subtrees of any node differ by no more than one. This property ensures that operations such as insertion, deletion, and lookup remain efficient, typically maintaining an average time complexity of O(logn)O(\log n). Understanding whether a binary tree is balanced can be crucial for optimizing tree operations and maintaining efficient data structures.

Understanding Balanced Trees

Definition

A binary tree is considered balanced if:

  1. The left and right subtrees’ heights differ by at most one.
  2. Both the left and right subtrees are balanced themselves.

Why Balancing Matters

Balanced trees guarantee more predictable performance for operations:

  • Insertion: Avoids skewed trees which could degrade performance to O(n)O(n).
  • Deletion: Simplifies rebalancing processes.
  • Search: Maintains logarithmic complexity, crucial for large datasets.

Determining if a Binary Tree is Balanced

Approach

The typical approach involves two main tasks:

  1. Calculate the height of left and right subtrees.
  2. Verify that the height difference is no more than one for every node.

Here's how you can implement this check in Python:

python
1class TreeNode:
2    def __init__(self, value=0, left=None, right=None):
3        self.value = value
4        self.left = left
5        self.right = right
6
7def is_balanced(root):
8    def check_balance(node):
9        if not node:
10            return 0
11
12        left_height = check_balance(node.left)
13        if left_height == -1:
14            return -1
15
16        right_height = check_balance(node.right)
17        if right_height == -1:
18            return -1
19
20        if abs(left_height - right_height) > 1:
21            return -1
22
23        return max(left_height, right_height) + 1
24
25    return check_balance(root) != -1
26
27# Example Usage
28# Constructing a balanced binary tree
29root = TreeNode(1)
30root.left = TreeNode(2)
31root.right = TreeNode(3)
32root.left.left = TreeNode(4)
33root.left.right = TreeNode(5)
34root.right.right = TreeNode(6)
35
36print(is_balanced(root))  # Output: True

Technical Explanation

  1. Recursive Approach:
    • Consider each node as the root of a subtree.
    • Recursively calculate the heights of both left and right subtrees.
    • Check if the current node’s subtree is height-balanced using the height difference condition.
  2. Height Representation:
    • A balanced subtree returns a valid height.
    • An unbalanced subtree returns -1 immediately, signaling imbalance.
  3. Efficiency:
    • This approach ensures each node is only visited once.
    • The time complexity is O(n)O(n) where nn is the number of nodes.

Key Points Summary

Key ConceptExplanation
Balanced DefinitionHeights of left/right subtrees differ by at most one.
ImportanceEnsures efficient tree operations (O(logn)O(\log n) for insert/search/delete).
Recursive CheckIncludes height calculation and balance verification for each node.
Time ComplexityO(n)O(n) due to single traversal of tree.
Imbalance DetectionIf any subtree is unbalanced, it propagates a -1 signal up the tree.

Additional Considerations

  • Complete vs. Balanced Trees:
    • Complete Trees are fully filled except possibly the last level, leading invariably to balanced nodes.
    • Balanced Trees focus solely on maintaining height properties, making them broadly applicable but less strict than complete trees.
  • AVL Trees:
    • A self-balancing binary tree where the difference between heights of left and right subtrees cannot be more than one for all nodes.
    • AVL trees maintain direct balance while performing insertions or deletions, dynamically adjusting subtrees to remain balanced.

In summary, understanding and ensuring that a binary tree is balanced is essential for optimizing tree operations, enhancing performance, and ensuring that the tree can handle various dynamic modifications efficiently. Implementing checks for tree balance not only safeguards operational efficiency but also strengthens the robustness of tree-based algorithms.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms