Welcome to the world of Data Structures and Algorithms! Today, we're going to learn about an important concept - Balanced Binary Trees. We'll also write a function to check if a given tree is balanced or not.
A binary tree is considered balanced if the difference between the heights of the left and right subtrees for every node is not more than 1. An unbalanced binary tree can lead to inefficient operations due to a skewed tree structure.
Balanced binary trees ensure that operations like insertion, deletion, and searching are more efficient, especially in large datasets. It prevents the tree from becoming a linked list, where every node needs to be traversed to find a specific value.
There are two main types of balanced binary trees:
Let's write a simple function to check if a given binary tree is balanced or not. We'll create a helper function to calculate the height of the tree recursively.
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def height(node):
if node is None:
return 0
return 1 + max(height(node.left), height(node.right))
def isBalanced(node):
if node is None:
return True
lh = height(node.left)
rh = height(node.right)
if abs(lh - rh) > 1:
return False
return isBalanced(node.left) and isBalanced(node.right)
# Test case
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print(isBalanced(root)) # Output: TrueIn this example, we create a simple binary tree and check if it's balanced using our isBalanced function.
What does the `height` function do?
That's it for today! You've learned about balanced binary trees, why they matter, and how to write a simple function to check if a given tree is balanced.
Stay tuned for more lessons on Data Structures and Algorithms! š”