Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Balanced Binary Tree in Python
In a binary tree, each node contains two children, i.e left child and right child. Let us suppose we have a binary tree and we need to check if the tree is balanced or not. A Binary tree is said to be balanced if the difference of height of left subtree and right subtree is less than or equal to 1.
Problem Examples
Example 1 - Balanced Tree
Output: True
Explanation: The height difference between left subtree (height 1) and right subtree (height 2) is |1-2| = 1, which is ? 1.
Example 2 - Unbalanced Tree
Output: False
Explanation: The height difference between left subtree (height 3) and right subtree (height 0) is |3-0| = 3, which is > 1.
Approach to Solve this Problem
The recursive approach to solve this problem is ?
- Calculate the height of left and right subtrees for each node
- Check if the absolute height difference is ? 1
- Recursively verify that both left and right subtrees are also balanced
- Return True only if current node and all subtrees are balanced
Method 1: Using Height Calculation
class TreeNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def get_height(node):
"""Calculate height of a tree"""
if node is None:
return 0
return 1 + max(get_height(node.left), get_height(node.right))
def is_balanced(root):
"""Check if binary tree is balanced"""
if root is None:
return True
# Get heights of left and right subtrees
left_height = get_height(root.left)
right_height = get_height(root.right)
# Check if current node is balanced and recursively check subtrees
return (abs(left_height - right_height) <= 1 and
is_balanced(root.left) and
is_balanced(root.right))
# Create balanced tree: [1, 2, 3, None, None, 6, 7]
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.right.left = TreeNode(6)
root.right.right = TreeNode(7)
if is_balanced(root):
print("Balanced")
else:
print("Not Balanced")
Balanced
Method 2: Optimized Single-Pass Solution
This approach calculates height and checks balance in a single traversal ?
class TreeNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def check_balance(node):
"""Returns (is_balanced, height)"""
if node is None:
return True, 0
# Check left subtree
left_balanced, left_height = check_balance(node.left)
if not left_balanced:
return False, 0
# Check right subtree
right_balanced, right_height = check_balance(node.right)
if not right_balanced:
return False, 0
# Check current node balance
height_diff = abs(left_height - right_height)
current_balanced = height_diff <= 1
current_height = 1 + max(left_height, right_height)
return current_balanced, current_height
def is_balanced_optimized(root):
"""Optimized balance check"""
balanced, _ = check_balance(root)
return balanced
# Test with unbalanced tree
root = TreeNode(1)
root.left = TreeNode(2)
root.left.left = TreeNode(4)
root.left.left.left = TreeNode(5)
root.right = TreeNode(3)
print("Optimized result:", is_balanced_optimized(root))
Optimized result: False
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Height Calculation | O(n²) | O(h) | Simple understanding |
| Single-Pass | O(n) | O(h) | Large trees |
Conclusion
A balanced binary tree has height difference ? 1 between left and right subtrees at every node. Use the optimized single-pass approach for better performance with large trees.
