sp23 Bse 106 DSA

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

Name : Muhammad Abid Dar

Reg no : SP23-BSE-106-B

Height-Balanced Trees :
In the field of computer science, a height-balanced tree is a binary search tree (BST) where the
difference in heights between the left and right subtrees of any node is bounded by a constant
value (typically 1 or 2). This ensures that search, insertion, and deletion operations have a
guaranteed logarithmic time complexity (O(log n)), regardless of the order in which elements
are added.

AVL Trees :
An AVL tree is a specific type of self-balancing binary search tree. It maintains the height-
balanced property by associating a balance factor with each node. The balance factor is the
difference between the heights of the left and right subtrees of a node. In an AVL tree, the
balance factor of every node must be within -1, 0, or +1.

Example:
Consider the following AVL tree:

/\

2 6

/\ /\

1 35 7

In this tree, each node's balance factor is shown within parentheses:

4 (-1)

/\

2 6 (1)

/\ /\

1 3 5 (0) 7 (-1)
As you can see, all balance factors fall within the allowed range, making this a balanced AVL
tree.

Insertion in AVL Trees :

1. Standard BST Insertion:

Insert the new node following the standard binary search tree insertion rules (traverse left for
smaller values, right for larger values).

2. Balance Factor Update:

As you traverse the tree during insertion, update the balance factor of each node you visit.

3. Rotation for Imbalance:

If a node's balance factor becomes -2 or +2 after insertion, perform a rotation to restore balance.
There are four possible rotation cases (left-left, left-right, right-right, right-left) depending on the
location of the imbalance and the direction of the insertion.

Deletion in AVL Trees :

1. Standard BST Deletion:

Delete the node following the standard binary search tree deletion rules (handle leaf nodes, one-
child nodes, and two-child nodes).

2. Balance Factor Update:

After deletion, update the balance factor of each node on the path from the deleted node back
to the root.

3. Rotation for Imbalance:

If a node's balance factor becomes -2 or +2 after deletion, perform a rotation to restore balance.
The rotation cases are similar to those in insertion.
Maintaining Balance :
AVL trees perform rotations to maintain balance when an insertion or deletion creates an
imbalance. These rotations effectively redistribute nodes in the tree, ensuring that the height
difference between left and right subtrees remains within the allowed bounds.

Time Complexity :
Due to the self-balancing property, all operations (search, insertion, deletion) in an AVL tree have
a guaranteed time complexity of O(log n) in the average and worst-case scenarios, making them
efficient for maintaining sorted data sets.

You might also like