Home » AKTU CSE Notes » AKTU Data Structure Unit 5 Notes KCS 301

AKTU Data Structure Unit 5 Notes KCS 301

Support this post with a reaction:

5,725 views

Trees are important non-linear data structures used to organize and store data in a hierarchical manner. A tree consists of a collection of nodes connected by edges, where one node is designated as the root node, and the remaining nodes are arranged in parent-child relationships.

Unlike linear data structures such as arrays, linked lists, stacks, and queues, where elements are organized sequentially, trees represent data in a hierarchical structure. This structure makes it easier to organize information and perform operations such as searching, insertion, deletion, and modification.

Trees are widely used in computer science applications such as database indexing, file systems, expression evaluation, hierarchical data organization, searching algorithms, and data compression.

In this unit, we study the fundamental terminology of trees, different types of binary trees, binary tree representations, and tree traversal techniques such as Inorder, Preorder, and Postorder. We also explore Binary Search Trees (BST), their operations, Threaded Binary Trees, Huffman Coding, AVL Trees, B-Trees, and Binary Heaps.

AKTU Data Structure UNIT 5 Syllabus

Trees: Basic terminology used with Tree, Binary Trees, Binary Tree Representation: Array Representation and Pointer(Linked List) Representation, Binary Search Tree, Strictly Binary Tree ,Complete Binary Tree . A Extended Binary Trees

Tree Traversal algorithms: Inorder, Preorder and Postorder, Constructing Binary Tree from given Tree Traversal, Operation of Insertation , Deletion, Searching & Modification of data in Binary Search . Threaded Binary trees, Traversing Threaded Binary trees. Huffman coding using Binary Tree. Concept & Basic Operations for AVL Tree , B Tree & Binary Heaps.

What Is a Tree in Data Structures?

A tree is a non-linear hierarchical data structure consisting of a collection of nodes connected by edges. It represents data in a parent-child relationship, where one node acts as the starting point and other nodes are connected below it in a hierarchical manner.

The topmost node of a tree is called the root node. Each node can contain data and links to its child nodes. A tree does not contain any cycles, and there is exactly one path from the root node to any other node in the tree.

Trees are widely used in computer science for representing hierarchical information, organizing data, searching, and efficient data processing.

Tree Data Structure

Tree Terminology

TermDefinition
NodeBasic element that stores data.
RootTopmost node of a tree.
EdgeConnection between two nodes.
ParentNode having one or more children.
ChildNode directly connected below a parent.
SiblingNodes having the same parent.
Leaf NodeNode having no children.
Internal NodeNode having at least one child.
Degree of NodeNumber of children of a node.
Degree of TreeMaximum degree of any node.
LevelPosition of a node in the tree. Root is at level 0.
DepthNumber of edges from the root to a node.
Height of NodeLongest path from the node to a leaf.
Height of TreeHeight of the root node.
SubtreeA tree formed by a node and its descendants.
AncestorAny node on the path from the root to a particular node.
DescendantAny node below a particular node.
ForestA collection of disjoint trees.

Properties of Trees

1. Number of Edges: A tree containing n nodes has exactly n-1 edges. This is because every node except the root is connected to exactly one parent node.

2. Unique Path: There is exactly one path between any two nodes in a tree. This means that two nodes cannot be connected through more than one distinct path.

3. Parent-Child Relationship: In a rooted tree, every node except the root has exactly one parent. The root node does not have a parent, but it may have one or more child nodes.

4. No Cycles: A tree does not contain any cycles. A cycle is a path that starts and ends at the same node without repeating other nodes. Therefore, it is impossible to return to a node by following a different path.

5. Connected Structure: A tree is a connected structure, which means that every node can be reached from every other node by following the edges. It cannot contain disconnected nodes or separate components.

6. Single Root Node: Every non-empty rooted tree has exactly one root node. It is the topmost node in the hierarchy, and all other nodes are connected to it directly or indirectly.

Example of a Tree Terminology

Consider a tree with 7 nodes.

  • Number of nodes = 7
  • Number of edges = 6
  • Root = A
  • Leaf nodes = D, E, F, G
  • Degree of root = 2

Tree Representations

A tree is a non-linear data structure that can be represented in computer memory using different methods. The choice of representation depends on the type of tree and the operations to be performed.

The two common methods of representing a general tree are Parent Array Representation and Linked Representation.

1. Parent Array Representation

In this representation, a tree is stored using an array in which each element represents a node and stores the index of its parent node.

  • Each node is assigned a unique index in the array.
  • The array element at each index stores the index of that node’s parent.
  • The root node has no parent, so its parent value is represented by -1.
  • This representation is simple and requires less memory when the tree structure is relatively static.

Example of Parent Array Representation

NodeParent
A-1
BA
CA
DB
EB

The root node has no parent, so it is represented using -1.

2. Linked List Representation

In linked representation, a tree is stored using dynamically allocated nodes connected through pointers. Each node contains data and one or more pointers that link it to other nodes.

For a general tree, each node commonly contains:

  • Data Field: Stores the value or information of the node.
  • First Child Pointer: Points to the first child of the node.
  • Next Sibling Pointer: Points to the next sibling of the node.
  • Parent Pointer (Optional): Points to the parent node, if required

Example of Linked Representation

struct Node {
    int data;
    struct Node *firstChild;
    struct Node *nextSibling;
};

What Is a Binary Tree?

A binary tree is a non-linear hierarchical data structure in which each node can have at most two children. These children are called the left child and the right child.

A binary tree starts with a root node, and each node can contain data along with links to its left and right child nodes. A node may have zero, one, or two children.

Binary trees are widely used in searching, sorting, expression evaluation, database indexing, and hierarchical data representation.A binary tree is commonly used in searching, sorting, expression evaluation, and hierarchical data representation.

Structure of a Binary Tree Node

Binary Tree

In a linked representation, each node of a binary tree is created dynamically and consists of three fields:

  1. Data Field: Stores the value or information contained in the node.
  2. Left Pointer: Stores the address of the left child node. If the node does not have a left child, this pointer is set to NULL.
  3. Right Pointer: Stores the address of the right child node. If the node does not have a right child, this pointer is set to NULL.

Properties of Binary Trees

Assuming the root is at level 0:

1. Maximum number of nodes at level l:

2l 2^l

2. Maximum number of nodes in a binary tree of height h:

2h+1−1 2^{h+1}-1

3. Minimum number of nodes in a binary tree of height h:

h+1 h+1

4. Maximum number of leaf nodes at height h:

2h 2^h

5. Minimum possible height of a binary tree containing n nodes:

⌈log2⁡(n+1)⌉−1 \lceil \log_2(n+1)\rceil-1

Types of Binary Trees

1. Full Binary Tree

A Full Binary Tree is a special type of binary tree in which every node has either zero or exactly two children. In other words, no node in a Full Binary Tree can have only one child.

Example of Full Binary Tree:

       A
      / \
     B   C
    / \
   D   E

Properties of Full Binary Tree:

  • Every internal node has exactly two children.
  • Leaf nodes have no children.

2. Complete Binary Tree

A complete binary tree is a binary tree in which all levels are completely filled except possibly the last level. The last level is filled from left to right.

Example of Complete Binary Tree:

       A
      / \
     B   C
    / \  /
   D  E F

Applications of Complete Binary Tree:

  • Binary Heaps: A complete binary tree that follows the heap property, where the parent node is either greater than or equal to (Max Heap) or smaller than or equal to (Min Heap) its children.
  • Priority Queues: A data structure in which elements are processed according to their priority rather than their insertion order

3. Perfect Binary Tree

A Perfect Binary Tree is a binary tree in which every internal node has exactly two children, and all leaf nodes are at the same level. In this type of tree, every level is completely filled with nodes.

Properties of Perfect Binary Tree:

  • Every internal node has exactly two children.
  • All leaf nodes are at the same level.
  • Every level is completely filled.

Example of Perfect Binary Tree:

         A
       /   \
      B     C
     / \   / \
    D   E F   G

For height h:

N=2h+1−1 N=2^{h+1}-1

4. Balanced Binary Tree

A Balanced Binary Tree is a binary tree in which the heights of the left and right subtrees of each node differ by at most a specified limit, usually one. This helps maintain a relatively uniform tree structure and improves the efficiency of operations such as searching, insertion, and deletion.

Properties of Balanced Binary Tree:

  • The heights of the left and right subtrees remain nearly equal.
  • The tree avoids becoming highly skewed.
  • Searching, insertion, and deletion can be performed efficiently.
  • AVL trees are a common example of height-balanced binary trees.

Example of Balanced Binary Tree:

       A
      / \
     B   C
    /     \
   D       E

Balanced trees improve searching and insertion performance.

5. Degenerate Binary Tree

A Degenerate Binary Tree is a special type of binary tree in which every parent node has exactly one child. In this tree, each node has either a left child or a right child, but not both. The structure of a degenerate binary tree resembles a linked list because all nodes are arranged in a single chain.

Example of Degenerate Binary Tree:

    A
     \
      B
       \
        C
         \
          D

It behaves similarly to a linked list.

6. Skewed Binary Tree

A Skewed Binary Tree is a special type of degenerate binary tree in which every node has exactly one child, except the leaf node. All nodes are arranged in a single direction, either towards the left or towards the right.

A Skewed Binary Tree resembles a linked list because each node is connected to only one child node. It is classified into two types based on the direction of the child nodes.

  • Left-skewed: A Left-Skewed Binary Tree is a binary tree in which every node has only a left child and no right child.
  • Right-skewed: A Right-Skewed Binary Tree is a binary tree in which every node has only a right child and no left child.

Binary Tree Representation

A binary tree can be represented in computer memory using different methods. The two commonly used methods are Array Representation and Linked Representation. Both methods are used to store nodes and maintain the parent-child relationships between them.

Representation of Binary Tree in Array

In array representation, the nodes of a binary tree are stored sequentially in an array. The position of each node in the array determines the location of its parent and children.

For a binary tree using 0-based indexing, the relationships are:

  • Root: index 0
  • Left child of node at index (i):
2i+1 2i+1

Right child of node at index (i):

2i+2 2i+2

Parent of node at index (i):

⌊i−12⌋ \left\lfloor\frac{i-1}{2}\right\rfloor

Binary Tree Traversals

Tree Traversal is the process of visiting or accessing every node of a binary tree exactly once in a specific order. It is used to process, display, search, or modify the data stored in the tree.

Binary tree traversal techniques are mainly classified into four methods:

  1. Inorder Traversal
  2. Preorder Traversal
  3. Postorder Traversal
  4. Level Order Traversal

Consider the following tree for the tree traversal methods:

        A
       / \
      B   C
     / \   \
    D   E   F

1. In order Traversal (Left – Root – Right)

Inorder Traversal is a Depth-First Search (DFS) technique in which the nodes of a binary tree are visited in the following order: first the left subtree, then the root node, and finally the right subtree.

Steps:

  1. Traverse the Left Subtree: Visit all nodes in the left subtree recursively using inorder traversal.
  2. Visit the Root Node: Process or display the data of the current root node.
  3. Traverse the Right Subtree: Visit all nodes in the right subtree recursively using inorder traversal.

Algorithm of In order Traversal

INORDER(root)
{
    if root != NULL
    {
        INORDER(root.left)
        VISIT(root)
        INORDER(root.right)
    }
}

Output:

D B E A C F

2. Pre order Traversal (Root – Left – Right)

Preorder Traversal is a Depth-First Search (DFS) technique in which the root node is visited first, followed by the left subtree and finally the right subtree. In this method, the parent node is processed before its child nodes.

Steps:

  1. Visit the Root Node: Process or display the data of the current root node.
  2. Traverse the Left Subtree: Visit all nodes in the left subtree recursively using preorder traversal.
  3. Traverse the Right Subtree: Visit all nodes in the right subtree recursively using preorder traversal.

Algorithm of Pre order Traversal

PREORDER(root)
{
    if root != NULL
    {
        VISIT(root)
        PREORDER(root.left)
        PREORDER(root.right)
    }
}

Output:

A B D E C F

Applications of Pre order Traversal

  • Used to create a copy of a binary tree.
  • Used to generate prefix expressions from expression trees.
  • Useful for displaying the hierarchical structure of a tree

3. Post order Traversal (Left – Right – Root)

Postorder Traversal is a Depth-First Search (DFS) technique in which the left subtree is visited first, followed by the right subtree, and finally the root node. In this method, the child nodes are processed before their parent node.

Steps:

  1. Traverse the Left Subtree: Visit all nodes in the left subtree recursively using postorder traversal.
  2. Traverse the Right Subtree: Visit all nodes in the right subtree recursively using postorder traversal.
  3. Visit the Root Node: Process or display the data of the current root node.

Algorithm of Post order Traversal

POSTORDER(root)
{
    if root != NULL
    {
        POSTORDER(root.left)
        POSTORDER(root.right)
        VISIT(root)
    }
}

Output:

D E B F C A

Applications of Post order Traversal

  • Used to delete a binary tree.
  • Used to generate postfix expressions from expression trees.
  • Useful for evaluating arithmetic expression trees.

4. Level Order Traversal

Level Order Traversal is a Breadth-First Search (BFS) technique in which the nodes of a binary tree are visited level by level, starting from the root node. At each level, the nodes are visited from left to right.

Unlike Inorder, Preorder, and Postorder Traversals, Level Order Traversal uses a Queue data structure to maintain the order in which nodes are visited.

Steps:

  1. Initialize the Queue: Create an empty queue and insert the root node into it.
  2. Check the Queue: Repeat the following steps until the queue becomes empty.
  3. Remove and Visit: Remove the front node from the queue and process or display its data.
  4. Insert Left Child: If the removed node has a left child, insert it into the queue.
  5. Insert Right Child: If the removed node has a right child, insert it into the queue.
  6. Repeat: Continue the process until all nodes have been visited.

Algorithm of Level Order Traversal

LEVELORDER(root)
{
    if root == NULL
        return

    Create an empty queue Q
    ENQUEUE(Q, root)

    while Q is not empty
    {
        node = DEQUEUE(Q)
        VISIT(node)

        if node.left != NULL
            ENQUEUE(Q, node.left)

        if node.right != NULL
            ENQUEUE(Q, node.right)
    }
}

Output:

A B C D E F

Operations on Binary Trees

A binary tree supports various operations to store, access, and modify the data present in its nodes. These operations help in managing the tree structure efficiently.

The main operations performed on a binary tree are:

  • Insertion
  • Deletion
  • Searching

1. Insertion

Insertion is the process of adding a new node to an existing binary tree while maintaining its structural properties.

In a general binary tree, a new node can be inserted at any available position, provided the binary tree structure is maintained. A commonly used method is Level Order Insertion, in which the new node is inserted at the first available position by traversing the tree level by level, from left to right.

Steps for Level Order Insertion:

  1. Create a new node with the given data.
  2. If the tree is empty, make the new node the root node.
  3. Otherwise, insert the root node into a queue.
  4. Remove a node from the front of the queue and check its left child.
  5. If the left child is empty, insert the new node there; otherwise, insert the left child into the queue.
  6. Check the right child. If it is empty, insert the new node there; otherwise, insert the right child into the queue.
  7. Repeat the process until the new node is inserted.

Insertion Algorithm

INSERT(root, data)
{
create a new node with data

if root == NULL
    return newNode

create an empty queue Q
enqueue(Q, root)

while Q is not empty:
    temp = dequeue(Q)

    if temp.left == NULL:
        temp.left = newNode
        return root
    else:
        enqueue(Q, temp.left)

    if temp.right == NULL:
        temp.right = newNode
        return root
    else:
        enqueue(Q, temp.right)

return root

}

Example of Insertion

Before insertion:

       A
      / \
     B   C

Insert D:

       A
      / \
     B   C
    /
   D

2. Searching

Searching is the process of finding a specific element or value in a binary tree. It involves checking the data stored in each node to determine whether the required element is present in the tree.

In a general binary tree, there is no fixed ordering of nodes. Therefore, searching may require visiting each node until the desired element is found or all nodes have been checked.

Steps for Searching:

  1. Start searching from the root node.
  2. Compare the data of the current node with the required element.
  3. If both values are equal, the element is found.
  4. Otherwise, search the left and right subtrees recursively.
  5. If the element is not found after checking all nodes, report that the element is not present in the tree.

Algorithm of Searching

SEARCH(root, key)
{
    if root == NULL
        return NOT_FOUND

    if root.data == key
        return FOUND

    if SEARCH(root.left, key) == FOUND
        return FOUND

    return SEARCH(root.right, key)
}

Example of Searching

Consider the following binary tree:

       10
      /  \
     20   30
    / \
   40  50

Search for the element 50.

Step 1: Start searching from the root node 10.

Step 2: Compare 10 with 50. Since they are not equal, search the left subtree.

Step 3: Visit node 20 and compare it with 50. Since they are not equal, continue searching.

Step 4: Visit node 40. Since it is not equal to 50, continue searching.

Step 5: Visit node 50. The required element is found.

Traversal Order: 10 → 20 → 40 → 50

Result: Element 50 is found in the binary tree.

Time complexity:

  • Best Case: O(1) – The required element is found at the root node during the first comparison.
  • Worst Case: O(n) – The required element is at the last node checked or is not present, so all \(n\) nodes may need to be visited.

3. Deletion

Deletion is the process of removing a specific node from an existing binary tree while maintaining its structural properties.

In a general binary tree, a commonly used deletion method is to replace the node to be deleted with the deepest rightmost node (the last node in level order traversal) and then remove that deepest rightmost node from its original position.

Steps for Deletion:

  1. Find the Target Node: Traverse the binary tree to locate the node that needs to be deleted.
  2. Find the Deepest Rightmost Node: Identify the deepest and rightmost node in the binary tree using level order traversal.
  3. Replace the Data: Copy the data of the deepest rightmost node into the target node.
  4. Delete the Deepest Rightmost Node: Remove the deepest rightmost node from its original position and update the corresponding parent pointer.

Deletion Algorithm

DELETE(root, key)
{
    if root == NULL
        return NULL

    if root.left == NULL AND root.right == NULL:
        if root.data == key:
            delete root
            return NULL
        else:
            return root

    create an empty queue Q
    enqueue(Q, root)

    target = NULL
    last = NULL
    parent = NULL

    while Q is not empty:
        temp = dequeue(Q)

Example of Deletion

Before deletion:

       10
/ \
20 30
/ \ /
40 50 60


Delete the node with value 20.

After Deletion

10
/ \
60 30
/ \
40 50

Construction of Binary Trees

A binary tree can be constructed using different traversal sequences. The structure of the tree can be uniquely determined when two suitable traversal sequences are given, provided that all node values are distinct.

One common method is to construct a binary tree using Inorder and Preorder Traversals.

1. Inorder and Preorder Traversals

  • Preorder Traversal (Root – Left – Right): Identifies the root node first because the first element in the preorder sequence is always the root.
  • Inorder Traversal (Left – Root – Right): Identifies the left and right subtrees because the elements before the root belong to the left subtree, while the elements after the root belong to the right subtree.

Example of Inorder and Preorder Traversals

Preorder:

A B D E C F

Inorder:

D B E A F C

Construction Steps:

  1. Identify the Root: The first element of preorder is A, so A becomes the root node.
  2. Divide the Inorder Sequence: Locate A in the inorder sequence.
    • Left subtree: D B E
    • Right subtree: F C
  3. Construct the Left Subtree: The next preorder elements are B D E. Therefore, B becomes the left child of A.
    • B has D as its left child.
    • B has E as its right child.
  4. Construct the Right Subtree: The remaining preorder elements are C F. Therefore, C becomes the right child of A.
    • C has F as its left child.
    • C has no right child.

Final Binary Tree:

           A
         /   \
        B     C
       / \   /
      D   E F

2. Inorder and Postorder

A binary tree can also be constructed using Inorder and Postorder Traversals.

  • Postorder Traversal (Left – Right – Root): Identifies the root node last because the last element in the postorder sequence is always the root.
  • Inorder Traversal (Left – Root – Right): Identifies the left and right subtrees by locating the root element in the inorder sequence.

Example of Inorder and Postorder

Postorder:

D E B F C A

Inorder:

D B E A F C

Construction Steps:

  1. Identify the Root: The last element of the postorder sequence is A, so A becomes the root node.
  2. Divide the Inorder Sequence: Locate A in the inorder sequence.
    • Left subtree: D B E
    • Right subtree: F C
  3. Construct the Left Subtree: The corresponding postorder elements are D E B. The last element B becomes the left child of A.
    • B has D as its left child.
    • B has E as its right child.
  4. Construct the Right Subtree: The remaining postorder elements are F C. The last element C becomes the right child of A.
    • C has F as its left child.
    • C has no right child.
  5. Repeat Recursively: Continue the same process until all nodes are placed in the binary tree.

Final Binary Tree:

    A
   / \
  B   C
 / \  /
D   E F

Binary Search Tree (BST)

A Binary Search Tree (BST) is a special type of binary tree in which nodes are arranged in a specific order to make searching, insertion, and deletion operations more efficient.

It follows the following properties:

  1. Left Subtree Property: All values in the left subtree of a node are smaller than the value of that node.
  2. Right Subtree Property: All values in the right subtree of a node are greater than the value of that node.
  3. Recursive Property: Both the left and right subtrees must also satisfy the Binary Search Tree properties.
  4. Root Property: The root node acts as the starting point for searching, insertion, and deletion operations.

Example of Binary Search Tree

          50
         /  \
        30   70
       / \   / \
      20 40 60 80

For the above tree:

  • Root = 50
  • Left subtree values = 20, 30, 40
  • Right subtree values = 60, 70, 80

BST Operations

          50
         /  \
        30   70
       / \   / \
      20 40 60 80

Use this tree as example for BST operations

1. Searching in BST

Searching in a Binary Search Tree (BST) is the process of finding a specific element by comparing the required value with the values stored in the nodes.

The BST property makes searching efficient because, at each step, one of the subtrees can be eliminated from consideration

Algorithm of Searching in BST

SEARCH(root, key)
{
    if root == NULL
        return NOT_FOUND

    if key == root.data
        return FOUND

    if key < root.data
        return SEARCH(root.left, key)

    else
        return SEARCH(root.right, key)
}

Example of Searching in BST:

Search for 40.

  • Compare 40 with 50.
  • Since 40 < 50, move left.
  • Compare 40 with 30.
  • Since 40 > 30, move right.
  • Element 40 is found.

2. Insertion in BST

Insertion in a Binary Search Tree (BST) is the process of adding a new node to the tree while maintaining the Binary Search Tree properties.

The new node is inserted at the appropriate position by comparing its value with the values of existing nodes.

Algorithm of Insertion in BST

INSERT(root, key)
{
    if root == NULL
        return NEW_NODE(key)

    if key < root.data
        root.left = INSERT(root.left, key)

    else if key > root.data
        root.right = INSERT(root.right, key)

    return root
}

Example of Insertion in BST :

Insert 35.

          50
         /  \
        30   70
       / \   / \
      20 40 60 80
         /
        35

3. Deletion in BST

Deletion in a Binary Search Tree (BST) is the process of removing a node from the tree while maintaining the Binary Search Tree properties.

Deletion in a BST is performed based on the number of children of the node to be deleted.

Deletion in a BST has three cases.

Case 1: Deleting a Leaf Node (Node with No Children)

  • Find the node to be deleted.
  • Remove the node directly from the tree.
  • Set the corresponding parent pointer to NULL.

Example: Delete 20.

          50
/ \
30 70
/ \ / \
35 40 60 80

Simply remove the node.

Case 2: Deleting a node with one child

  • Find the node to be deleted.
  • Connect its parent directly to its only child.
  • Remove the node from the tree.

Example: If node 30 has only child 40, deleting 30 will connect its parent directly to 40.

Case 3: Deleting a node with two children

  • Find the node to be deleted.
  • Find its inorder successor (the smallest node in its right subtree) or inorder predecessor (the largest node in its left subtree).
  • Replace the value of the node to be deleted with the successor or predecessor value.
  • Delete the successor or predecessor from its original position. This replacement node will have at most one child.

Then delete the replacement node from its original location.

4. BST Modification

BST Modification refers to the process of updating the data stored in a Binary Search Tree (BST) while maintaining its ordering properties. It includes adding new nodes, removing existing nodes, and modifying the values of existing nodes.

A Binary Search Tree follows these important properties:

  • All values in the left subtree of a node are smaller than the node’s value.
  • All values in the right subtree of a node are greater than the node’s value.
  • Both left and right subtrees must also satisfy the BST properties.

Modifying a Node in BST:

When the value of an existing node needs to be changed, it is important to maintain the BST ordering property. Directly changing the value may violate the BST structure.

A safe method is:

  1. Search: Find the node containing the old value.
  2. Delete: Remove the node containing the old value using the BST deletion procedure.
  3. Insert: Insert the updated value into its correct position using the BST insertion procedure.
  4. Verify: Ensure that the BST properties are maintained after modification.

Example of BST Modification:

If a node containing 30 needs to be modified to 45:

  • Search for the node containing 30.
  • Delete the node containing 30.
  • Insert the new value 45 at its correct position.

Threaded Binary Trees

A Threaded Binary Tree is a special type of binary tree in which the NULL pointers are replaced with special links called threads. These threads point to the inorder predecessor or inorder successor of a node.

In an ordinary binary tree, many left and right pointers may contain NULL values. Threaded binary trees make use of these unused pointers to establish additional connections between nodes.

Purpose and Advantages of Threaded Binary Trees

  • Makes use of otherwise unused NULL pointers.
  • Allows tree traversal without recursion.
  • Eliminates the need for an additional stack during inorder traversal.
  • Makes it easier to access the inorder predecessor and successor of a node.

Types of Threaded Binary Trees

1. Left Threaded Binary Tree

A Left Threaded Binary Tree is a binary tree in which NULL left pointers are replaced with threads pointing to the inorder predecessor of the node.

2. Right Threaded Binary Tree

A Right Threaded Binary Tree is a binary tree in which NULL right pointers are replaced with threads pointing to the inorder successor of the node.

3. Fully Threaded Binary Tree (Double Threaded Binary Tree)

A Fully Threaded Binary Tree is a binary tree in which both NULL left and NULL right pointers are replaced with threads.

  • Left threads point to the inorder predecessor.
  • Right threads point to the inorder successor.
Types of Threaded Binary Trees

Node Structure of Threaded Binary Trees

struct Node {
    int data;
    struct Node *left;
    struct Node *right;
    int lthread;
    int rthread;
};

Here:

  • lthread = 1 means left pointer is a thread.
  • rthread = 1 means right pointer is a thread.

Huffman Coding

Huffman Coding is a lossless data compression technique that assigns variable-length binary codes to characters based on their frequencies of occurrence. Characters that appear more frequently are assigned shorter binary codes, while characters that appear less frequently are assigned longer binary codes.

It is based on a greedy algorithm and uses a special binary tree called a Huffman Tree to generate efficient codes.

Huffman Coding reduces the total number of bits required to represent data without losing any original information. It is widely used in file compression, image compression, and data transmission.

Characters with higher frequencies receive shorter codes, while characters with lower frequencies receive longer codes.

Huffman Coding

Expected cost of encoding a letter:
1.0.45 + 3-0.41+ 4.0.14 = 2.24

Principles of Huffman Coding

Huffman Coding is a lossless data compression technique that assigns variable-length binary codes to characters based on their frequencies of occurrence. It follows these important principles:

1. Greedy Algorithm: It uses a greedy approach by repeatedly combining the two nodes with the lowest frequencies to construct the Huffman Tree.

2. Prefix-Free Codes: It generates prefix-free codes, meaning that no character’s code is the prefix of another character’s code.

3. Unique Decoding: Since no code is the prefix of another, encoded data can be decoded uniquely without requiring separators between codes.

4. Efficient Compression: Frequently occurring characters are assigned shorter binary codes, while less frequently occurring characters are assigned longer codes, reducing the total number of bits required to represent the data.

5. Lossless Compression: It preserves the original data completely, allowing the exact original message to be recovered during decoding.

Huffman Coding Algorithm

  1. Create a leaf node for each character.
  2. Insert all nodes into a min-priority queue.
  3. Remove the two nodes with minimum frequencies.
  4. Create a new internal node with frequency equal to their sum.
  5. Make the two nodes its children.
  6. Insert the new node into the queue.
  7. Repeat until one node remains.
  8. Assign 0 to left edges and 1 to right edges.
  9. The code for a character is the path from root to leaf.

Example of Huffman Coding

Consider the following character frequencies:

CharacterFrequency
A5
B9
C12
D13
E16
F45

The Huffman algorithm repeatedly combines the two smallest frequencies:

  • 5 + 9 = 14
  • 12 + 13 = 25
  • 14 + 16 = 30
  • 25 + 30 = 55
  • 45 + 55 = 100

The exact binary codes depend on the left/right assignment at each combination.

AVL Tree

An AVL Tree is a self-balancing Binary Search Tree (BST) in which the difference between the heights of the left and right subtrees of any node is at most one.

AVL Trees maintain balance automatically after insertion and deletion operations using a technique called Tree Rotation. This balancing helps prevent the tree from becoming skewed and ensures efficient searching, insertion, and deletion.

AVL stands for Adelson-Velsky and Landis.

AVL Trees

AVL Rotations

AVL Rotations are special restructuring operations performed on an AVL tree to restore its height balance when an insertion or deletion causes the tree to become unbalanced.

Rotations rearrange the nodes without changing the Binary Search Tree ordering property. There are four types of AVL rotations:

  • LL Rotation
  • RR Rotation
  • LR Rotation
  • RL Rotation

Case 1: LL Rotation (Right Rotation)

LL Rotation occurs when a node becomes unbalanced due to the insertion of a new node into the left subtree of its left child. This causes the tree to become heavier on the left side. A single Right Rotation is performed on the unbalanced node to restore the AVL tree balance.

Example: Insert 30, 20, 10.

Before:

       30
      /
     20
    /
   10

After right rotation:

      20
     /  \
    10  30

Case 2: RR Rotation (Left Rotation)

RR Rotation occurs when a node becomes unbalanced due to the insertion of a new node into the right subtree of its right child. This causes the tree to become heavier on the right side. A single Left Rotation is performed on the unbalanced node to restore the AVL tree balance.

Example: Insert 10, 20, 30.

Before:

   10
     \
      20
        \
         30

After left rotation:

      20
     /  \
    10  30

Case 3: LR Rotation

LR Rotation occurs when a node becomes unbalanced due to the insertion of a new node into the right subtree of its left child. This causes the tree to become heavier in a left-right direction.

A double rotation is performed to restore the AVL tree balance:

  1. Perform a Left Rotation on the left child of the unbalanced node.
  2. Perform a Right Rotation on the unbalanced node.

Example: Insert 30, 10, 20.

       30              20
      /               /  \
     10      →       10  30
       \
        20

Case 4: RL Rotation

RL Rotation occurs when a node becomes unbalanced due to the insertion of a new node into the left subtree of its right child. This causes the tree to become heavier in a right-left direction.

A double rotation is performed to restore the AVL tree balance.

  1. Perform a Right Rotation on the right child of the unbalanced node.
  2. Perform a Left Rotation on the unbalanced node.

Example: Insert 10, 30, 20.

    10                20
      \              /  \
      30      →     10  30
     /
    20

B-Tree

A B-Tree is a self-balancing multiway search tree in which each node can contain multiple keys and multiple children. Unlike a Binary Search Tree, where each node can have at most two children, a B-Tree allows multiple children in a single node.

B-Trees maintain their balance automatically during insertion and deletion operations. All leaf nodes remain at the same level, which ensures efficient searching and data retrieval.

B-Trees are widely used in database indexing, file systems, and storage management because they reduce the number of disk accesses required to retrieve data.

Structure of a B-Tree

A B-Tree node contains the following main components:

Number of Children: A node with \(k\) keys can have at most \(k+1\) children.

Keys: Store the actual data values in sorted order. These keys divide the values into different ranges and help determine the direction of searching.

Child Pointers: Store links or addresses of the child nodes. These pointers connect the nodes and maintain the hierarchical structure of the B-Tree.

Number of Keys: Stores or maintains the count of keys present in the node.

B-Tree

Properties of B-Tree of Order m

A B-Tree of order m is a self-balancing multiway search tree in which each node can have multiple keys and child nodes. It follows specific rules to maintain balance and support efficient searching, insertion, and deletion.

The important properties are:

  1. Maximum Children: Each node can have a maximum of m children.
  2. Maximum Keys: Each node can contain a maximum of m-1 keys.
  3. Minimum Children: Every non-root internal node must have at least [ m/2 ] children.
  4. Minimum Keys: Every non-root node must contain at least [ m/2 – 1 ] keys.
  5. Same Leaf Level: All leaf nodes must be present at the same level.
  6. Root Node: The root may contain fewer keys than other nodes. If it is not a leaf, it must have at least two children.
  7. Sorted Keys: All keys within a node are stored in ascending order.
  8. Balanced Structure: A B-Tree always maintains its balanced structure, ensuring that all leaf nodes remain at the same level.

Operations on B-Tree

1. B-Tree Insertion

Insertion is the process of adding a new key to a B-Tree while maintaining its sorted order and balancing properties.

Steps for Insertion:

  1. Find the Leaf Node: Search for the appropriate leaf node where the new key should be inserted.
  2. Insert the Key: Insert the new key into the leaf node in sorted order.
  3. Check Overflow: If the node contains more than m-1 keys, it causes an overflow.
  4. Split the Node: Divide the overflowing node into two nodes and promote the middle key to the parent node.
  5. Handle Parent Overflow: If the parent node also exceeds its maximum key limit, split it and promote its middle key.
  6. Create a New Root: If the root node splits, create a new root containing the promoted middle key.

2. B-Tree Deletion

Deletion is the process of removing a key from a B-Tree while maintaining its sorted order, minimum key requirements, and balanced structure.

Deletion in a B-Tree mainly involves the following cases:

  1. Deleting from a Leaf Node: If the key is present in a leaf node and the node has more than the minimum number of keys, remove the key directly.
  2. Deleting from an Internal Node: If the key is present in an internal node, replace it with its inorder predecessor (largest key in the left subtree) or inorder successor (smallest key in the right subtree), and then delete the replacement key from its original position.
  3. Borrowing from a Sibling: If a node has fewer than the minimum required keys, borrow a key from an adjacent sibling through the parent, provided the sibling has an extra key.
  4. Merging Nodes: If borrowing is not possible, merge the underfilled node with a sibling and a separating key from the parent.
  5. Root Adjustment: If the root becomes empty after merging, its only child becomes the new root.

Binary Heaps

A Binary Heap is a special type of complete binary tree that satisfies a specific ordering property called the Heap Property. It is commonly used to implement Priority Queues and Heap Sort.

In a Binary Heap, each parent node follows a particular relationship with its child nodes. Based on this relationship, Binary Heaps are classified into two main types: Max Heap and Min Heap.

A Binary Heap is generally represented using an array, which makes insertion, deletion, and accessing the root element efficient.

Binary Heap

A binary heap is a complete binary tree that satisfies the heap-order property.

Types of Binary Heap

1. Max Heap

A Max Heap is a complete binary tree in which the value of every parent node is greater than or equal to the values of its child nodes. Therefore, the root node always contains the maximum value in the heap

Properties of Max Heap

  • Every parent node is greater than or equal to its children.
  • The root node contains the largest element.
  • It follows the structure of a complete binary tree.
  • The left and right subtrees must also satisfy the Max Heap property.

Example of Max Heap

             90
           /    \
          70     80
         / \     / \
        40  50  60  30

The maximum element is at the root.

2. Min Heap

A Min Heap is a complete binary tree in which the value of every parent node is smaller than or equal to the values of its child nodes. Therefore, the root node always contains the minimum value in the heap.

Properties of Min Heap

  • Every parent node is smaller than or equal to its children.
  • The root node contains the smallest element.
  • It follows the structure of a complete binary tree.
  • The left and right subtrees must also satisfy the Min Heap property.

Example of Min Heap

             10
           /    \
          20     15
         / \     / \
        30  40  25  35

The minimum element is at the root.

Operations on Heap

1. Heap Representation

A Binary Heap is commonly represented using an array rather than linked nodes. Since a binary heap is a complete binary tree, its elements can be stored sequentially in an array without requiring additional pointers to connect parent and child nodes.

In an array representation, the elements are stored level by level, starting from the root node and moving from left to right at each level.

For a binary heap using 0-based indexing, the following formulas are used to find the parent and child positions of any node:

OperationFormula
Parent(i-1)/2
Left Child(2i+1)
Right Child(2i+2)

2. Heap Insertion

Heap Insertion is the process of adding a new element to a Max Heap or Min Heap while maintaining the complete binary tree structure and heap property.

Steps for Insertion:

  1. Insert the Element: Add the new element at the end of the heap (next available position in the array).
  2. Compare with Parent: Compare the newly inserted element with its parent node.
  3. Check Heap Property: If the heap property is violated, swap the new element with its parent.
  4. Repeat the Process: Continue comparing and swapping with the parent until the heap property is restored or the element reaches the root.
  5. Complete Insertion: Stop when the heap property is satisfied.

3. Heap Deletion

Heap Deletion is the process of removing the root element from a heap while maintaining the complete binary tree structure and heap property. In a Max Heap, the root contains the maximum element. Therefore, deletion removes the maximum element.

Steps for Deletion in a Max Heap:

  1. Remove the Root: Remove the root node, which contains the maximum element.
  2. Replace the Root: Move the last element of the heap to the root position.
  3. Compare with Children: Compare the new root with its left and right children.
  4. Swap Elements: If the Max Heap property is violated, swap the root with its largest child.
  5. Repeat the Process: Continue comparing and swapping downward until the heap property is restored or the element reaches a leaf position.
  6. Complete Deletion: Stop when the Max Heap property is satisfied.

Important Data Structure AKTU Examination Questions – Unit 5

  • Explain tree terminology with a suitable diagram.
  • Explain different types of binary trees with diagrams.
  • Explain array and linked representations of binary trees.
  • Explain inorder, preorder, postorder, and level order traversal with algorithms.
  • Construct a binary tree from inorder and preorder traversal sequences.
  • Explain insertion, searching, and deletion operations in BST with examples.
  • Explain threaded binary trees and their types.
  • Explain Huffman coding with an example.
  • Explain AVL tree rotations with suitable diagrams.
  • Explain B-Tree properties, insertion, and deletion.
  • Explain binary heaps and their operations.
  • Explain Heap Sort with an example.

Explore More Resources of Data Structures

ResourceDescriptionLink
Data Structures Question BankPractice important questions, MCQs, and exam-oriented questions on Data Structures.Data Structure Previous Year Questions and Answers →
Data Structures Previous Year Question PapersPrepare using previous year university question papers for Data Structures.Data Structure Previous Year Question Papers →

Explore Other AKTU Data Structures Units

Continue your AKTU Data Structures preparation with complete unit-wise notes, explanations, diagrams, algorithms, and important questions.

Data Structures UnitsPage Navigation
Unit 1 – Introduction to Data StructuresRead Unit 1 Notes→
Unit 2 – Stacks, Queues and RecursionRead Unit 2 Notes→
Unit 3 – Sorting and searchingRead Unit 3 Notes→
Unit 4 – Graphs and Graph AlgorithmsRead Unit 5 Notes→

Explore More Study Materials

Visit Quescol Home Page

Explore more AKTU B.Tech CSE notes, syllabus, and examination preparation resources on Quescol.