Amina Parveen: Assignment#4 Data Structures
Amina Parveen: Assignment#4 Data Structures
Amina Parveen: Assignment#4 Data Structures
Assignment#4
Data Structures
TREES
1. Balanced Trees:
class node {
public:
int data;
node* left;
node* right;
};
if (root == NULL)
return 1;
lh = height(root->left);
rh = height(root->right);
return 0;
}
int max(int a, int b)
{
return (a >= b) ? a : b;
}
int height(node* node)
{
/* base case tree is empty */
if (node == NULL)
return 0;
return 1 + max(height(node->left),
height(node->right));
}
node* newNode(int data)
{
node* Node = new node();
Node->data = data;
Node->left = NULL;
Node->right = NULL;
return (Node);
}
int main()
{
node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->left->left->left = newNode(8);
if (isBalanced(root))
cout << "Tree is balanced";
else
cout << "Tree is not balanced";
return 0;
}
2. AVL Search Trees
AVL tree is a self-balancing binary search tree in which each node maintains extra information called a balance
factor whose value is either -1, 0 or +1.
AVL tree got its name after its inventor Georgy Adelson-Velsky and Landis.
Operations on AVL Trees:
Left Rotate.
Right Rotate.
Left-Right And Right-Left Rotate.
Insertion and deletion.
3. Insertion and Deletion on AVL trees:
Algorithm for Insertion
1:-A newNode is always inserted as a leaf node with balance factor equal to 0.
2: Go to the appropriate leaf node to insert a newNode using the following recursive steps. Compare newKey with rootKey of the
current tree.
a. If newKey < rootKey, call insertion algorithm on the left subtree of the current node until the leaf node is reached.
b. Else if newKey > rootKey, call insertion algorithm on the right subtree of current node until the leaf node is reached.
c. Else, return leafNode.
3: Compare leafKey obtained from the above steps with newKey:
d. If newKey < leafKey, make newNode as the leftChild of leafNode.
e. Else, make newNode as rightChild of leafNode.
4: Update balanceFactor of the nodes
5: If the nodes are unbalanced, then rebalance the node.
a. If balanceFactor > 1, it means the height of the left subtree is greater than that of the right subtree. So, do a right rotation or left-right
rotation
a. If newNodeKey < leftChildKey do right rotation.
b. Else, do left-right rotation.
b. If balanceFactor < -1, it means the height of the right subtree is greater than that of the left subtree. So, do right rotation or right-left
rotation
c. If newNodeKey > rightChildKey do left rotation.
d. Else, do right-left rotation.
Deletion Algorithm
1. Locate nodeToBeDeleted (recursion is used to find nodeToBeDeleted in the code used below).
2 : There are three cases for deleting a node:
a. If nodeToBeDeleted is the leaf node (ie. does not have any child), then remove nodeToBeDeleted.
b. If nodeToBeDeleted has one child, then substitute the contents of nodeToBeDeleted with that of the child. Remove the child.
c. If nodeToBeDeleted has two children, find the inorder successor w of nodeToBeDeleted (ie. node with a minimum value of key in the right subtree).
a: Substitute the contents of nodeToBeDeleted with that of w.
b: Remove the leaf node w.
C: Update balanceFactor of the nodes.
D: Rebalance the tree if the balance factor of any of the nodes is not equal to -1, 0 or 1.
a. If balanceFactor of currentNode > 1,
If balanceFactor of leftChild >= 0, do right rotation.
a. Right-rotate for balancing the tree
b. Else do left-right rotation.
b. If balanceFactor of currentNode < -1,
a. If balanceFactor of rightChild <= 0, do left rotation.
b. Else do right-left rotation.
4. B-Trees
B-tree is a special type of self-balancing search tree in which each node can contain more than one key
and can have more than two children. It is a generalized form of the binary search tree.
It is also known as a height-balanced m-way tree.
Algorithm
1. Starting from the root node, compare k with the first key of the node.
If k = the first key of the node, return the node and the index.
2. If k.leaf = true, return NULL (i.e. not found).
3. If k < the first key of the root node, search the left child of this key recursively.
4. If there is more than one key in the current node and k > the first key, compare k with the next key in the node.
If k < next key, search the left child of this key (ie. k lies in between the first and the second keys).
Else, search the right child of the key.
5. Repeat steps 1 to 4 until the leaf is reached.
5. Searching, Inserting, Deleting operation in B-Trees
Searching:
Search is similar to the search in Binary Search Tree. Let the key to be searched be k. We start from the root
and recursively traverse down. For every visited non-leaf node, if the node has the key, we simply return the
node. Otherwise, we recur down to the appropriate child (The child which is just before the first greater key) of
the node. If we reach a leaf node and don’t find k in the leaf node, we return NULL.
Logic:
Searching a B-Tree is similar to searching a binary tree. The algorithm is similar and goes with recursion. At
each level, the search is optimized as if the key value is not present in the range of parent then the key is
present in another branch. As these values limit the search they are also known as limiting value or separation
value. If we reach a leaf node and don’t find the desired key then it will display NULL.
Insertion Algorithm
1) Initialize x as root.
2) While x is not leaf, do following
a) Find the child of x that is going to be traversed next. Let the child be y.
b) If y is not full, change x to point to y.
c) If y is full, split it and change x to point to one of the two parts of y. If k is smaller than mid key in y, then
set x as the first part of y. Else second part of y. When we split y, we move a key from y to its parent x.
3) The loop in step 2 stops when x is leaf. x must have space for 1 extra key as we have been splitting all
nodes in advance. So simply insert k to x.
Let us understand the algorithm with an example tree of minimum degree ‘t’ as 3 and a sequence of integers
10, 20, 30, 40, 50, 60, 70, 80 and 90 in an initially empty B-Tree.
Initially root is NULL. Let us first insert
Deletion Algorithm
Deletion from a B-tree is more complicated than insertion, because we can delete a key from any node-not just
a leaf—and when we delete a key from an internal node, we will have to rearrange the node’s children
Algorithm
1. If the key k is in node x and x is a leaf, delete the key k from x.
2. If the key k is in node x and x is an internal node, do the following.
a) If the child y that precedes k in node x has at least t keys, then find the predecessor k0 of k in the sub-tree
rooted at y. Recursively delete k0, and replace k by k0 in x. (We can find k0 and delete it in a single downward
pass.)
b) If y has fewer than t keys, then, symmetrically, examine the child z that follows k in node x. If z has at least
t keys, then find the successor k0 of k in the subtree rooted at z. Recursively delete k0, and replace k by k0 in
x. (We can find k0 and delete it in a single downward pass.)
c) Otherwise, if both y and z have only t-1 keys, merge k and all of z into y, so that x loses both k and the
pointer to z, and y now contains 2t-1 keys. Then free z and recursively delete k from y.
3. If the key k is not present in internal node x, determine the root x.c(i) of the appropriate subtree that must
contain k, if k is in the tree at all. If x.c(i) has only t-1 keys, execute step 3a or 3b as necessary to guarantee that
we descend to a node containing at least t keys. Then finish by recursing on the appropriate child of x.
a) If x.c(i) has only t-1 keys but has an immediate sibling with at least t keys, give x.c(i) an extra key by
moving a key from x down into x.c(i), moving a key from x.c(i) ’s immediate left or right sibling up into x, and
moving the appropriate child pointer from the sibling into x.c(i).
b) If x.c(i) and both of x.c(i)’s immediate siblings have t-1 keys, merge x.c(i) with one sibling, which involves
moving a key from x down into the new merged node to become the median key for that node.
Since most of the keys in a B-tree are in the leaves, deletion operations are most often used to delete keys from
leaves. The recursive delete procedure then acts in one downward pass through the tree, without having to back
up. When deleting a key in an internal node, however, the procedure makes a downward pass through the tree
but may have to return to the node from which the key was deleted to replace the key with its predecessor or
successor (cases 2a and 2b).
6. B+- trees
A B+ tree is an advanced form of a self-balancing tree in which all the values are present in the leaf level. An
important concept to be understood before learning B+ tree is multilevel indexing. In multilevel indexing, the
index of indices is created as in figure below. It makes accessing the data easier and faster
Properties
All leaves are at the same level.
Each node except root can have a maximum of m children and at least m/2 children.
Each node can contain a maximum of m - 1 keys and a minimum of ⌈m/2⌉ - 1 keys.
Algorithm
• Start from the root node. Compare k with the keys at the root node [k1, k2, k3,......km - 1].
• If k < k1, go to the left child of the root node.
• Else if k == k1, compare k2. If k < k2, k lies between k1 and k2. So, search in the left child of k2.
• If k > k2, go for k3, k4,...km-1 as in steps 2 and 3.
• Repeat the above steps until a leaf node is reached.
Red-Black tree is a self-balancing binary search tree in which each node contains an extra bit for denoting the
color of the node, either red or black.
Red Property: If a red node has children, then, the children are always black.
Depth Property: For each node, any simple path from this node to any of its descendant leaf has the same
black depth (the number of black nodes).
Algorithm to insert a node
Following steps are followed for inserting a new element into a red-black tree:
• Check if the tree is empty (ie. whether x is NIL). If yes, insert newNode as a root node and color it black.
• Compare newKey with rootKey.
• Else, make newNode as leftChild.
A splay tree is a self-balancing tree, but AVL and Red-Black trees are also self-balancing trees then. What makes the splay
tree unique two trees. It has one extra property that makes it unique is splaying.
A splay tree contains the same operations as a Binary search tree, i.e., Insertion, deletion and searching, but it also contains
one more operation, i.e., splaying. So. all the operations in the splay tree are followed by splaying.
Rotations