UNIT III
LINKED LISTS &
TREES
CO3: Illustrate the outcome of various operations on data structures.
Syllabus
Trees • AVL Tree B Tree,
• Introduction to Tree, • B+ Tree.
• Tree Terminology
• Binary Tree
• Binary Search Tree
• Strictly Binary Tree,
• Complete Binary Tree,
• Tree Traversal,
• Threaded Binary Tree,
Trees: Introduction
• Specialized data structure to store data in hierarchical manner.
• Hierarchicalstructure that is used to represent and organize data in a way
that is easy to navigate and search.
• Consists
of a central node, structural nodes, and sub-nodes, which are
connected via edges.
• Data structure has roots, branches, and leaves connected.
• Topmost node of the tree is called the root.
• Nodes below it are called the child nodes.
• Eachnode can have multiple child nodes, and these child nodes can also
have their own child nodes, forming a recursive structure.
Trees: Tree Terminology
• Parent Node: predecessor of a
node, {B} is the parent node of
{D, E}.
• Child Node: immediate
successor of a node, {D, E} are
the child nodes of {B}.
• Root Node: topmost node, does
not have any parent node, {A{ is
root node
• Leaf Node or External Node:
nodes which do not have any
child nodes, {I, J, K, F, G, H}
• Ancestor of a Node: Any
predecessor nodes on the path of
the root , {A,B} are the ancestor
nodes of the node {E}
Trees: Tree Terminology
• Descendant: A node x is a
descendant of another node y if and
only if y is an ancestor of x.
• Sibling: Children of the same parent
node are called siblings. {D,E} are
called siblings.
• Level of a node: count of edges on
the path from the root node to that
node. The root node has level 0.
• Internal node: A node with at least
one child
• Neighbour of a Node: Parent or
child nodes of that node
• Subtree: Any node of the tree along
with its descendant.
Importance of tree data structure
• Store information that naturally forms a hierarchy. For example, the
file system on a computer:
• Trees
(with some ordering e.g., BST) provide moderate
access/search (quicker than Linked List and slower than arrays).
• Trees
provide moderate insertion/deletion (quicker than Arrays and
slower than Unordered Linked Lists).
• LikeLinked Lists and unlike Arrays, Trees don’t have an upper limit
on the number of nodes as nodes are linked using pointers.
Properties of data structure
• Numberof edges: Connection between the nodes, a tree with N
nodes would have N-1 edges
• Depth of node: Length of path from root to that node
• Height of node: length of the longest path from the node to a
leaf node of the tree.
• Heightof tree: length of the longest path from the root of the
tree to a leaf node of the tree.
• Degree of a node: total count of subtrees attached to that node
Trees: Binary Tree
• Non-linear data structure where each node has at most two children (left
child and right child).
• Concept of root and leaf
• Representation: Data, pointer to left child and pointer to right child
Trees: Tree Traversal
• Variousways to visit all
the nodes of the tree.
• Process of visiting or
accessing each node of
the tree exactly once in
a certain order.
• Treetraversal algorithms
help us to visit and
process all the nodes of
the tree.
• Sincetree is not a linear
data structure, there are
multiple nodes which we
can visit after visiting a
certain node.
In order
• Inorder traversal visits the node in
the order: Left -> Root -> Right
Algorithm for Inorder Traversal:
Inorder(tree)
• Traverse the left subtree, i.e., call
Inorder(left->subtree)
• Visit the root.
• Traverse the right subtree, i.e., call
Inorder(right->subtree)
#include <stdio.h> struct Node* node =
#include <stdlib.h> (struct Node*)malloc(sizeof(struct
Node));
struct Node { node->data = v;
int data; node->left = node->right = NULL;
struct Node *left, *right; return node;
}; }
void printInorder(struct Node* node) { int main() {
if (node == NULL) struct Node* root = newNode(1);
return; root->left = newNode(2);
root->right = newNode(3);
// First recur on left subtree root->left->left = newNode(4);
printInorder(node->left); root->left->right = newNode(5);
root->right->right = newNode(6);
// Now deal with the node
printf("%d ", node->data); printf("Inorder traversal of binary tree is: \
n");
// Then recur on right subtree printInorder(root);
printInorder(node->right);
} return 0;
}
struct Node* newNode(int v) {
Preorder Traversal
• Preorder traversal is defined as a
type of tree traversal that follows
the Root-Left-Right
Algorithm for Preorder Traversal:
Preorder(tree)
• Visit the root.
• Traverse the left subtree, i.e., call
Preorder(left->subtree)
• Traverse the right subtree, i.e., call
Preorder(right->subtree)
Preorder program
#include<stdio.h>
#include<malloc.h> int main(){
struct node{ struct node *p = createNode(4);
int data; struct node *p1 = createNode(1);
struct node* left; struct node *p2 = createNode(6);
struct node* right; struct node *p3 = createNode(5);
}; struct node *p4 = createNode(2);
// 4
struct node* createNode(int data){ // /\
struct node *n; // 1 6
n = (struct node *) malloc(sizeof(struct node)); // / \
n->data = data; // 5 2
n->left = NULL;
n->right = NULL; // Linking the root node with left and right children
return n; p->left = p1;
} p->right = p2;
p1->left = p3;
void preOrder(struct node* root){ p1->right = p4;
if(root!=NULL){
printf("%d ", root->data); preOrder(p);
preOrder(root->left); return 0;
preOrder(root->right); }
} Output
} 41526
Post-order Traversal
• Postorder traversal visits the node
in the order: Left -> Right -> Root
Algorithm for Postorder Traversal:
Algorithm Postorder(tree)
• Traverse the left subtree, i.e., call
Postorder(left->subtree)
• Traverse the right subtree, i.e., call
Postorder(right->subtree)
• Visit the root
#include<stdio.h> } struct node *p4 = createNode(2);
#include<malloc.h> } // Finally The tree looks like this:
// 4
struct node{ void postOrder(struct node* root){ // /\
int data; if(root!=NULL){ // 1 6
struct node* left; postOrder(root->left); // / \
struct node* right; postOrder(root->right); // 5 2
}; printf("%d ", root->data);
} // Linking the root node with left and
struct node* createNode(int data){ } right children
struct node *n; p->left = p1;
n = (struct node *) void inOrder(struct node* root){ p->right = p2;
malloc(sizeof(struct node)); if(root!=NULL){ p1->left = p3;
n->data = data; inOrder(root->left); p1->right = p4;
n->left = NULL; printf("%d ", root->data);
n->right = NULL; inOrder(root->right); preOrder(p);
return n; // Finally returning the } printf("\n");
created node postOrder(p);
}
} printf("\n");
int main(){ inOrder(p);
void preOrder(struct node* root){ return 0;
struct node *p = createNode(4);
if(root!=NULL){ }
struct node *p1 = createNode(1);
printf("%d ", root->data); 41526
struct node *p2 = createNode(6);
preOrder(root->left); 52164
struct node *p3 = createNode(5);
preOrder(root->right); 51246
Level order traversal
• LevelOrder Traversal visits all nodes
present in the same level completely
before visiting the next level.
Algorithm for Level Order Traversal:
LevelOrder(tree)
• Create an empty queue Q
• Enqueue the root node of the tree to Q
• Loop while Q is not empty
• Dequeue a node from Q and visit it
• Enqueue the left child of the dequeued
node if it exists
• Enqueue the right child of the dequeued
node if it exists
Trees: Full/Strictly Binary Tree
• Strict
binary tree is a binary tree
having all of its nodes with a
degree of 2 or 0.
• Each of its nodes either have 2
children or is a leaf node.
Trees: Complete Binary Tree
• Nodes are not added to a new level until the
preceding level is fully filled
• because a Binary tree is known as a Complete
Binary tree
• if all the nodes are added from the left.
• Allof the nodes must be as far to the left as
feasible in the final level.
• One or two internal nodes may give birth to
offspring. However, as the nodes must be
inserted starting from the left, only one internal
node may have only one child, while the rest will
all have 0 or 2 children.
Trees: Threaded Binary Tree
• One half of the link fields contain NULL
values which results in wastage of storage
space.
• in
order to effectively manage the space, a
method was devised by Perlis and Thornton
• NULL links are replaced with special links
known as threads, known as threaded binary
tree.
• Each node in a threaded binary tree either
contains a link to its child node or thread to
other nodes in the tree.
Trees: Binary Search Tree
• Organizing and storing data in a sorted manner.
• At most two children, a left child and a right
child.
• BST follows all properties of binary tree
• Leftchild containing values less than the parent
node.
• Right child containing values greater than the
parent node.
• Allows for efficient searching, insertion, and
deletion operations on the data stored in the tree.
BST Properties
• left subtree of a node contains only nodes
with keys lesser than the node’s key.
• The right subtree of a node contains only
nodes with keys greater than the node’s key.
• The left and right subtree each must also be
a binary search tree.
• There must be no duplicate nodes
BST operations
• Searching a node in BST: First root, than if lesser go on left side if greater go
on right side.
• Insert a node into a BST: Always inserted at the leaf
• Delete a Node of BST
• Traversal (In order traversal of BST) : gives nodes in non-decreasing order.,
visit the left child first, then the root, and then the right child.
Advantages and Disadvantages
Advantages:
• Fast search
• In-order traversal
Disadvantages:
• Skewed trees
• Additional time required
• Efficiency
Trees: AVL Tree
•Self-balancing Binary Search Tree
(BST)
• Tree height is kept to a
minimum so that a very fast
runtime is guaranteed for
searching
• Difference between heights of left and
right subtrees for any node cannot be
more than one.
• The only difference between a regular
Binary Search Tree and an AVL Tree is
that AVL Trees do rotation operations in
addition, to keep the tree balance.
• Called as the balance factor.
• Named after its inventors, Georgy
Adelson-Velsky and Evgenii Landis.
AVL Traversal
• Left Rotation:
• When a node is added
into the right subtree of
the right subtree, if the
tree gets out of balance,
we do a single left
rotation.
• Right Rotation:
• If a node is added to the
left subtree of the left
subtree, the AVL tree may
get out of balance, we do
a single right rotation.
AVL traversal
• Left-Right Rotation:
•A left-right rotation is a
combination in which first left
rotation takes place after that
right rotation executes.
• Right-Left Rotation:
•A right-left rotation is a
combination in which first
right rotation takes place after
that left rotation executes.
Trees: B Tree
•B tree is a self-balancing tree, and it is a m-way tree
• It is a generalized form of the binary search tree.
• Large number of keys that they can store in a single node
•A B-tree is a self-balancing tree where all the leaf nodes are at the same
level.
• Allows for efficient searching, insertion and deletion of records.
• Because of all the leaf nodes being on the same level, the access time of
data is fixed regardless of the size of the data set
Characteristics of B-Tree?
• Balanced: B-trees are balanced, meaning that all leaf nodes are at the same level.
This ensures that the time required to access data in the tree remains constant,
regardless of the size of the data set.
• Self-balancing: B-trees are self-balancing, which means that as new data is
inserted or old data is deleted, the tree automatically adjusts to maintain its
balance.
• Multiple keys per node: B-trees allow multiple keys to be stored in each node.
This allows for efficient use of memory and reduces the height of the tree, which in
turn reduces the number of disk accesses required to retrieve data.
• Ordered: B-trees maintain the order of the keys, which makes searching and range
queries efficient.
• Efficient for large data sets: B-trees are particularly useful for storing and
retrieving large amounts of data, as they minimize the number of disk accesses
required to find a particular piece of data.
Trees: B+ Tree
• In B Tree, Keys and records both can be stored in the internal as
well as leaf nodes.
• In B+ tree, records (data) can only be stored on the leaf nodes
while internal nodes can only store the key values.
• The leaf nodes of a B+ tree are linked together in the form of a
singly linked lists to make the search queries more efficient.
• All the leaf nodes are connected to each other through a pointer
• internal nodes contain only pointers and leaf nodes contain
records.