0% found this document useful (0 votes)
7 views

Unit-IV Tree structures

The document provides an overview of tree structures in data structures, focusing on various types of binary trees, their properties, and traversal methods. It discusses binary search trees (BST), AVL trees, and their operations, including insertion, deletion, and searching, along with the significance of AVL trees over traditional BSTs. Additionally, it touches on binary heaps, highlighting their properties and types.

Uploaded by

madhan95ece
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Unit-IV Tree structures

The document provides an overview of tree structures in data structures, focusing on various types of binary trees, their properties, and traversal methods. It discusses binary search trees (BST), AVL trees, and their operations, including insertion, deletion, and searching, along with the significance of AVL trees over traditional BSTs. Additionally, it touches on binary heaps, highlighting their properties and types.

Uploaded by

madhan95ece
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 71

UNIT-IV TREE STRUCTURES

Tree ADT
 Descendant: Any successor node on the path from that node to leaf node.
{D,I,J} or {E,K}are descendant node of node{B}
Types of Binary Tree in Data Structure
 Full Binary Tree
A full binary tree is a tree where every node has either 0 or 2
children.

 Complete Binary Tree


A complete binary tree is a tree where all levels are fully filled except
possibly the last level, which is filled from left to right.
 Perfect Binary Tree
A perfect binary tree is a tree where all internal nodes have exactly
two children and all leaf nodes are at the same level.

 Degenerate (or Pathological) Binary Tree


A degenerate binary tree is a tree where each parent node has only
one child. This makes the tree look like a linked list.
Binary Tree Implementation using Linked List
Binary Tree Traversals
Types
1. In-order Traversal (Left, Root, Right)
2. Pre-order Traversal (Root, Left, Right)
3. Post-order Traversal (Left, Right, Root)
4. Level-order Traversal (Breadth-First)
1. In-order Traversal (Left, Root, Right)
In in-order traversal, the nodes are recursively visited in this
order: left subtree, root node, and then the right subtree.

In-order Traversal: 4, 2, 5, 1, 3
Steps:
 Visit the left subtree: 4
 Visit the root: 2
 Visit the right subtree: 5
 Visit the root: 1
 Visit the right subtree: 3
2. Pre-order Traversal (Root, Left, Right)
In pre-order traversal, the nodes are recursively visited in this
order: root node, left subtree, and then the right subtree.

Pre-order Traversal: 1, 2, 4, 5, 3
Steps:
 Visit the root: 1
 Visit the left subtree: 2
 Visit the left subtree: 4
 Visit the right subtree: 5
 Visit the right subtree: 3
3. Post-order Traversal (Left, Right, Root)
In post-order traversal, the nodes are recursively visited in
this order: left subtree, right subtree, and then the root node.

Post-order Traversal: 4, 5, 2, 3, 1
Steps:
 Visit the left subtree: 4
 Visit the right subtree: 5
 Visit the root: 2
 Visit the right subtree: 3
 Visit the root: 1

4.Level-order Traversal (Breadth-First): In level-order


traversal, the nodes are visited level by level from left to
right. This traversal uses a queue data structure to keep track
of nodes.
Level-order Traversal: 1, 2, 3, 4, 5
Steps:
 Visit the root: 1
 Visit the nodes at the next level: 2, 3
 Visit the nodes at the next level: 4, 5

Time and Space Complexity of Binary Tree

Worst Case Time


Operation Complexity Space Complexity

Insertion O(n) O(n)

Deletion O(n) O(n)

Search O(n) O(n)

Traversal (In-order, O(n) O(h) (where h is the


Pre-order, Post-
height of the tree)
order)

Construct a binary tree from preorder and inorder


Pre-order: 1,2,4,8,9,10,11,5,3,6,7 (Root Left Right)
In-order: 8,4,10,9,11,2,5,1,6,3,7 (Left Root Right)
--

Construct a binary tree from postorder and inorder


Post-order: 9,1,2,12,7,5,3,11,4,8 (Left Right Root)
In-order: 9,5,1,7,2,12,8,4,3,11 (Left Root Right)
Binary Expression Trees
The expression tree is a binary tree in which each internal
node corresponds to the operator and each leaf node
corresponds to the operand.
Inorder traversal of expression tree produces infix
expression
same with postorder traversal it gives postfix expression
same with preorder traversal it gives prefix expression.
For constructing an expression tree we use a stack. We loop
through input expression and do the following for every
character.
1. If a character is an operand push that into the stack
2. If a character is an operator pop two values from the
stack make them its child and push the current node
again.
In the end, the only element of the stack will be the root of
an expression tree.
3. an operator ‘*’ will going read, so two pointers to trees
are popped, a new tree is formed and a pointer to it is
pushed onto the stack

an operator ‘+’ will going read, so two pointers to trees are


popped, a new tree is formed and a pointer to it is pushed
onto the stack
Binary search tree(BST)
In a BST, each node is a part of the tree that holds a value. Each node
can have up to two children nodes. The node at the top is called the
root.
The main rule of a BST is that for any node:
 All the values in the left child and its descendants are smaller
than the node's value.
 All the values in the right child and its descendants are greater
than the node's value.
This structure helps to quickly find, add, or remove values from the
tree.
Binary Search Tree Properties
1. Node Structure
Each node in a BST contains three parts:
 Data: The value stored in the node.
 Left Child: A pointer/reference to the left child node.
 Right Child: A pointer/reference to the right child node.
2. Binary Tree
A BST in data structure is a type of binary tree, which means each
node can have at most two children: left and right.
3. Ordered Nodes
 Left Subtree: For any given node, all the values in its left
subtree are smaller than the value of the node.
 Right Subtree: For any given node, all the values in its right
subtree are greater than the value of the node.
4. No Duplicate Values
A BST in data structure does not contain duplicate values. Each value
must be unique to maintain the order property.
5. Recursive Definition
Each subtree of a BST is also a BST. This means the left and right
children of any node are roots of their own Binary Search Trees.

Binary Search Tree Operations in Data Structure


1. Insertion
Insertion in binary search tree includes adding a new node in a way
that maintains the BST property: for any node, all values in its left
subtree are smaller, and all values in its right subtree are greater.
Algorithm:
 Start at the root node.
 Compare the value to be inserted with the current node's value.
 If the value is smaller, move to the left child.
 If the value is greater, move to the right child.
 Repeat steps 2-4 until you find an empty spot.
 Insert the new node at the empty spot.

Example:
Insert the value 8 into the following BST:
Step-by-Step Insertion:
 Start at the root (10).
 8 is less than 10, move to the left child (5).
 8 is greater than 5, move to the right child (7).
 8 is greater than 7, move to the right child of 7 (which is
empty).
 Insert 8 as the right child of 7.
Result:
2. Deletion
Binary search tree node deletion involves removing a node and
reorganizing the tree to maintain the BST property.
There are three cases to handle:
 Node with no children (leaf node)
 Node with one child
 Node with two children
Algorithm:
 No Child (Leaf Node): Simply remove the node.
 One Child: Remove the node and replace it with its child.
 Two Children: Find the in-order predecessor (largest value in
the left subtree) or in-order successor (smallest value in the
right subtree), replace the node's value with the
predecessor/successor, and delete the predecessor/successor.
Example:
Delete the value 5 from the following BST:
Step-by-Step Deletion:
 Start at the root (10).
 5 is less than 10, move to the left child (5).
 Node 5 has two children. Find the in-order successor (smallest
value in the right subtree of 5), which is 7.
 Replace 5 with 7.
 Delete node 7.

Result:

3. Searching
Searching in a binary search tree involves finding a node with a given
value by leveraging the BST property to reduce the number of
comparisons.
Algorithm:
 Start at the root node.
 Compare the target value with the current node's value.
 If the value is equal, the search is successful.
 If the value is smaller, move to the left child.
 If the value is greater, move to the right child.
 Repeat steps 2-5 until you find the value or reach an empty spot
(unsuccessful search).
Example:
Search for the value 8 in the following BST:

Step-by-Step Searching:
 Start at the root (10).
 8 is less than 10, move to the left child (5).
 8 is greater than 5, move to the right child (7).
 8 is greater than 7, move to the right child (8).
 8 is equal to 8, search is successful.
AVL Tree
 In an AVL data structure, each node has a balance factor.
 This balance factor is the difference height between the left
and right subtrees.
 The balance factor can only be -1, 0, or 1. If the balance factor
gets outside this range, the tree does a rotation to fix itself.
 This keeps the tree short and wide, making it faster to search,
insert, and delete items.
 This makes AVL trees very useful in applications like databases
and memory management, where we need to quickly find or
update information.

Properties of AVL Tree


 Balanced Tree
An AVL tree is always balanced. This means that the heights of the
left and right subtrees of any node differ by at most one.
 Height-Balanced Property
The difference in height (also called the balance factor) between the
left and right subtrees of any node is -1, 0, or 1.
 Self-Balancing
An AVL tree automatically performs rotations to maintain balance
after every insertion and deletion.
 Binary Search Tree Properties
An AVL tree follows the properties of a binary search tree (BST). This
means that for any node, the left subtree contains only nodes with
values less than the node's value, and the right subtree contains
only nodes with values greater than the node's value.
 Rotations
To maintain balance, an AVL tree uses four types of rotations: left
rotation, right rotation, left-right rotation, and right-left rotation.

Balance Factor of AVL Tree


The balancing factor (BF) of a node in an AVL tree is defined as the
height difference between its left and right subtrees.
For a node N, the balancing factor is calculated as:
BF(N) = height (left subtree) − height (right subtree)
Properties:
The balancing factor can be -1, 0, or 1 for a balanced AVL tree.
 BF = -1: The right subtree is one level higher than the left
subtree.
 BF = 0: The left and right subtrees are of equal height.
 BF = 1: The left subtree is one level higher than the right
subtree.
Operations on AVL Tree Data Structure
1. Insertion
Insertion in an AVL tree involves adding a new key while ensuring the
tree remains balanced. After inserting a new node, the balance factor
of each node is checked, and rotations are performed if necessary to
maintain the AVL property.
Algorithm:
 Perform a standard BST insertion.
 Update the height of the current node.
 Calculate the balance factor of the current node.
 Perform rotations if the node becomes unbalanced.
Example:
Insert keys

into an AVL tree.


2. Deletion
Deletion in an AVL tree involves removing a node and then ensuring
the tree remains balanced. After deleting a node, the balance factor
of each node is checked, and rotations are performed if necessary to
maintain the AVL property.
Algorithm:
 Perform a standard BST (Binary Search Tree)deletion.
 Update the height of the current node.
 Calculate the balance factor of the current node.
 Perform rotations if the node becomes unbalanced.
AVL Tree Rotations
Rotations in AVL tree are operations performed to maintain the
balance of the tree after insertions or deletions.
There are four types of rotations: Left Rotation, Right Rotation, Left-
Right Rotation, and Right-Left Rotation. Each rotation helps to
rebalance the tree when a node becomes unbalanced.
1. Left Rotation
A left rotation is performed when a node's right subtree is heavier
than its left subtree (balance factor < -1). This rotation shifts the
balance to the left.
Algorithm:
 Let the unbalanced node be x.
 Let y be the right child of x.
 Let z be the right child of y.
 Perform the rotation by making y the new root of the subtree.
 Now x be the left child of y and z be the right child of y.
2. Right Rotation
A right rotation is performed when a node's left subtree is heavier
than its right subtree (balance factor > 1). This rotation shifts the
balance to the right.
Algorithm:
 Let the unbalanced node be z.
 Let y be the left child of z.
 Let x be the left child of y.
 Perform the rotation by making y the new root of the subtree.
 Now x be the left child of y and z be the right child of y.
3. Left-Right (LR) Rotation
A left-right or LR rotation in AVL tree is performed when a node's left
subtree has a right-heavy child, causing the balance factor of the
left subtree to be less than zero. This rotation is a combination of a
left rotation followed by a right rotation.
Algorithm:
 Perform a left rotation on the left child.
 Perform a right rotation on the original unbalanced node.

4. Right-Left (RL) Rotation


A right-left or RL rotation in AVL tree is performed when a node's
right subtree has a left-heavy child, causing the balance factor of
the right subtree to be greater than zero. This rotation is a
combination of a right rotation followed by a left rotation.
Algorithm:
 Perform a right rotation on the right child.
 Perform a left rotation on the original unbalanced node.
Significance of AVL Trees over Binary Search Trees
A Binary Search Tree (BST) does not guarantee a balanced structure.
In the worst case (e.g., inserting sorted data), the height of the tree
becomes O(n), turning it into a linked list. This degrades the
performance of operations like insertion, deletion, and search to
linear time.
AVL Tree Advantages:
 AVL Tree is a self-balancing BST.
 It maintains a balance factor for each node (difference in height
of left and right subtrees).
 Ensures the height remains O(log n) for all operations.
 Provides better performance in the worst case compared to
normal BSTs.
Time Complexities:
Operation BST (Worst Case) AVL Tree
Insertion O(n) O(log n)
Deletion O(n) O(log n)
Search O(n) O(log n)
Binary Heap(Max heap or Min heap)
 A Heap is a complete binary tree where the value of each
node satisfies the heap property.
There are two types of heaps:
 Max Heap: The key at a parent node is greater than or equal to
the keys of its children.
 Min Heap: The key at a parent node is less than or equal to the
keys of its children.
Complete Binary Tree
 All levels are completely filled except possibly the last level.
 The last level has all keys as left as possible.
Max Heap

Min Heap
Properties of Heaps
Property Max Heap Min Heap
Root node Largest element Smallest element
Relationship Parent ≥ Children Parent ≤ Children
Complete Binary Complete Binary
Structure
Tree Tree
Implementation Array-based Array-based

Array Representation of Heap


 Indexing starts at 1 for simplicity.
 For a node at index i:
o Left Child: 2i
o Right Child: 2i + 1
o Parent: i // 2

Building a Max Heap


Algorithm: BUILD-MAX-HEAP
1. Given an unordered array A of size n
2. Start from the last non-leaf node: n//2
3. Apply MAX-HEAPIFY from i = n//2 to 1

PSEUDOCODE
MAX-HEAPIFY(A, i)
1. l = 2i
2. r = 2i + 1
3. largest = i
4. if l ≤ heap-size and A[l] > A[largest]
5. largest = l
6. if r ≤ heap-size and A[r] > A[largest]
7. largest = r
8. if largest ≠ i
9. swap A[i] and A[largest]
10. MAX-HEAPIFY(A, largest)
Time Complexity
 BUILD-MAX-HEAP: O(n)
 MAX-HEAPIFY: O(log n)

Building a Min Heap


Algorithm: BUILD-MIN-HEAP
1. Given an unordered array A of size n
2. Start from i = n//2 to 1
3. Apply MIN-HEAPIFY

PSEUDOCODE
MIN-HEAPIFY(A, i)
1. l = 2i
2. r = 2i + 1
3. smallest = i
4. if l ≤ heap-size and A[l] < A[smallest]
5. smallest = l
6. if r ≤ heap-size and A[r] < A[smallest]
7. smallest = r
8. if smallest ≠ i
9. swap A[i] and A[smallest]
10. MIN-HEAPIFY(A, smallest)
Time Complexity
 BUILD-MIN-HEAP: O(n)
 MIN-HEAPIFY: O(log n)

Applications of Heap
 Priority Queues
 Heap Sort
 Graph algorithms like Dijkstra and Prim

1. Insertion Operation in Binary Heap


Steps for Insertion (Min or Max Heap):
1. Insert the new element at the end of the array (bottom of
heap).
2. Compare the inserted node with its parent.
3. Swap if heap property is violated.
4. Repeat "bubble up" until heap property is restored.
Algorithm – Insert (Max Heap):
INSERT(A, key)
1. heap_size = heap_size + 1
2. A[heap_size] = key
3. i = heap_size
4. while i > 1 and A[parent(i)] < A[i]
5. swap A[i] and A[parent(i)]
6. i = parent(i)

********************************************************
2. Deletion Operation in Binary Heap
Steps for Deletion (Delete Root):
1. Replace root element with the last element in the heap.
2. Decrease heap size.
3. Apply heapify (percolate down) from root.
4. Restore heap property.
Algorithm – Delete (Max Heap):
DELETE-MAX(A)
1. if heap_size < 1
2. return error "heap underflow"
3. max = A[1]
4. A[1] = A[heap_size]
5. heap_size = heap_size - 1
6. MAX-HEAPIFY(A, 1)
7. return max
Multi-way Search Tree
Definition:
A Multi-way Search Tree (also called an m-way search tree) is a
generalization of a Binary Search Tree (BST) where each internal node
can have more than two children.
In an m-way search tree:
 Each node can contain up to m–1 keys.
 It can have at most m children.
 Keys are stored in sorted order within each node.
 Children are organized such that:
o All values in the i-th child are between the (i–1)th and i-th
key.
 Multi-way search trees are efficient structures when multiple
keys need to be stored in sorted order and accessed quickly.
They are widely used in database indexing and file systems.
Properties:
1. Each node with k keys has k + 1 children.
2. Keys in each node are kept in sorted order.
3. All subtrees follow the same multi-way search rule.
4. Efficient for indexing large databases and external memory
access.

Example (3-way Search Tree, i.e., m = 3)


Let us insert the following keys into a 3-way search tree:
[10, 20, 5, 6, 12, 30, 7, 17]

Step-by-step Insertion:
1. Insert 10: becomes the root.
2. Insert 20: root = [10, 20]
3. Insert 5: root = [5, 10, 20] (node now has 3 keys)
4. Insert 6: node is full → split
o Middle key 10 promoted
o Left = [5, 6], Right = [20], Root = [10]
5. Insert 12: Goes to right child → [20, 12] → sorted → [12, 20]
6. Insert 30: Right child becomes [12, 20, 30] → Full → split
o Promote 20, left = [12], right = [30], update root = [10, 20]
7. Insert 7: Goes to left child → [5, 6], becomes [5, 6, 7]
8. Insert 17: Goes to middle child → [12], becomes [12, 17]

Final Tree Diagram:


Advantages:
 Faster search, insertion, and deletion than BST in large data
sets.
 Reduces height of tree compared to binary trees.
 Good for disk-based and database applications (like B-trees).

You might also like