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

Unit-6 Trees

Uploaded by

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

Unit-6 Trees

Uploaded by

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

NON LINEAR DATA STRUCTURE-

TREES
Unit-4
NON LINEAR DATA STRUCTURES
� In non-linear data structure, the data values are
not arranged in order and a data item is
connected to several other data items.
� It uses memory efficiently. Free contiguous
memory is not required for allocating data items.
� Examples-
⚫ Trees and Graphs.
TREES
� Tree is a hierarchical data structure which stores the
information naturally in the form of hierarchy style.
� Tree is one of the most powerful and advanced data
structures.
� It is a non-linear data structure compared to arrays,
linked lists, stack and queue.
� It represents the nodes connected by edges.
� Tree is a collection of elements called Nodes, where
each node can have arbitrary number of children.
EXAMPLE Root

A Level - 0

Level - 1
B C
Parent Node
D E F G Level - 2

Child Node
H I Siblings Level - 3

Subtree

Leaf Node
� The above figure represents structure of a tree. Tree
has 2 subtrees.

⚫ A is a parent of B and C.
⚫ B is called a child of A and
⚫ B is also parent of D and E
IMPORTANT TERMS
� Path − Path refers to the sequence of nodes along the edges of a tree.
� Root − The node at the top of the tree is called root. There is only one
root per tree and one path from the root node to any node.
� Parent − Any node except the root node has one edge upward to a
node called parent.
� Child − The node below a given node connected by its edge downward
is called its child node.
� Leaf − The node which does not have any child node is called the leaf
node.
� Subtree − Subtree represents the descendants of a node.
� Visiting − Visiting refers to checking the value of a node when control
is on the node.
� Traversing − Traversing means passing through nodes in a specific
order.
� Levels − Level of a node represents the generation of a node. If the
root node is at level 0, then its next child node is at level 1, its
grandchild is at level 2, and so on.
� keys − Key represents a value of a node based on which a search
operation is to be carried out for a node.
BINARY TREE
� A tree whose elements have at most 2 children is
called a binary tree.
� Since each element in a binary tree can have only 2
children, we typically name them the left child and
right child.
� A tree is represented by a pointer to the topmost
node in tree.
� If the tree is empty, then value of root is NULL.
� A Tree node contains following parts.
1. Data
2. Pointer to left child
3. Pointer to right child
STRUCTURE OF NODE IN TREES
struct node
{
int data;
struct node *left;
struct node *right;
};
TRAVERSAL IN TREES
� Traversal is a process to visit all the nodes of a
tree print their values.
� Because, all nodes are connected via edges (links)
we always start from the root (head) node.
� We cannot randomly access a node in a tree.
� There are three ways to traverse a tree −
⚫ Pre-order Traversal
⚫ In-order Traversal
⚫ Post-order Traversal
PRE-ORDER TRAVERSAL
DATA- LEFT- RIGHT (DLR)

� In this traversal method,


⚫ the root node is visited first,
⚫ then the left subtree and
⚫ finally the right subtree.
� We should always remember that every node
may represent a subtree itself.
� Examples solved in notebook
SAMPLE EXAMPLE

� We start from A, and following pre-order traversal,


we first visit A itself and then move to its left
subtree B.
� B is also traversed pre-order.
� The process goes on until all the nodes are visited.
� The output of pre-order traversal of this tree will be −

A→B→D→E→C→F→G
ALGORITHM &FUNCTION (RECURSIVE)
Algorithm
Until all nodes are traversed −
� Step 1 − Visit root node.
� Step 2 − Recursively traverse left subtree. (Preorder left-
subtree)
� Step 3 − Recursively traverse right subtree. (Preorder
right- subtree)

Function
void preorder( struct node *tnode)
{
if(tnode)
{
printf(“%d”, & tnode->data);
preorder(tnode->leftchild);
preorder(tnode->rightchild);
}
}
NON RECURSIVE FUNCTION-PREORDER
void preorder(struct btreenode *root )
{
while(isempty(&stk))
{
push(&stk, root);
while(root!=NULL)
{
//Print data
printf(“%d”, root->data);
//Push right value into stack
push(&stk, root->right);
//Move to left
root=root->left;
}
if(isempty)
return;
root=pop(&stk);
}
IN-ORDER TRAVERSAL
LEFT- DATA- RIGHT (LDR)

� In this traversal method,


⚫ the left subtree is visited first,
⚫ then the root and
⚫ later the right sub-tree.
� We should always remember that every node
may represent a subtree itself.
� If a binary tree is traversed in-order, the output
will produce sorted key values in an ascending
order.
� Examples solved in notebook
SAMPLE EXAMPLE

� We start from A, and following In-order traversal, we


first visit node A itself and then the left subtree B.
� B is also traversed In-order.
� The process goes on until all the nodes are visited.
� The output of In-order traversal of this tree will be −

D→B→E→A→F→C→G
ALGORITHM &FUNCTION (RECURSIVE)
Algorithm
Until all nodes are traversed −
� Step 1 − Recursively traverse left subtree. (Inorder left-subtree)
� Step 2 − Visit root node.
� Step 3 − Recursively traverse right subtree. (Inorder right-
subtree)

Function
void inorder( struct node *tnode)
{
if(tnode)
{
inorder(tnode->leftchild);
printf(“%d”, & tnode->data);
inorder(tnode->rightchild);
}
}
NON RECURSIVE FUNCTION-INORDER
void inorder(struct btreenode *root )
{
while(isempty(&stk))
{
push(&stk, root);
while(root!=NULL)
{
push(&stk, root->left);
root=root->left;
}
if(isempty)
return;
root=pop(&stk);
printf(“%d”, root->data);
root=root->right;
}
}
POST-ORDER TRAVERSAL
LEFT – RIGHT - DATA (LRD)

� In this traversal method,


⚫ the left subtree is traversed first and
⚫ Then the right subtree
⚫ And finally the root node is visited

� We should always remember that every node


may represent a subtree itself.

� Examples solved in notebook


SAMPLE EXAMPLE

� We start from A, and following post-order traversal, we


first visit left sub-tree of A and then right subtree of A
� B is also traversed post-order.
� The process goes on until all the nodes are visited.
� The output of post-order traversal of this tree will be −

D→E→B→F→G→C→A
ALGORITHM & FUNCTION (RECURSIVE)
Algorithm
Until all nodes are traversed −
� Step 1− Recursively traverse left subtree. (Postorder left-subtree)
� Step 2 − Recursively traverse right subtree. (Postorder right-
subtree)
� Step 3 − Visit root node

Function
void postorder( struct node *tnode)
{
if(tnode)
{
postorder(tnode->leftchild);
postorder(tnode->rightchild);
printf(“%d”, & tnode->data);
}
}
NON RECURSIVE FUNCTION-POSTORDER
void postorder(struct btreenode *root )
{
while(isempty(&stk)
{
while(root!=NULL)
{
//Push the right
push(&stk, -(root->right));
//Move to left
root=root->left;
push(&stk, root->left);
}
if(isempty)
return;
root=pop(&stk);
if (root>0)
printf(“%d”, root->data);
else
push(&stk, -(root));
}
TYPES OF BINARY TREES
� Full Binary Tree
� Complete Binary Tree
� Binary Search Tree
� Expression Tree
FULL BINARY TREE
� A full binary tree (sometimes proper binary tree
or 2-tree) is a tree in which every node other than
the leaves has two children.
COMPLETE BINARY TREE

� A Binary Tree is complete Binary Tree if all


levels are completely filled except possibly the
last level
� The last level has all keys as left as possible
BINARY SEARCH TREE

� A Binary Search Tree (BST) is a tree in which all the


nodes follow the below-mentioned properties −
⚫ The left sub-tree of a node has a key less than or equal to
its parent node's key.
⚫ The right sub-tree of a node has a key greater than to its
parent node's key.
� Thus, BST divides all its sub-trees into two segments;
the left sub-tree and the right sub-tree and can be
defined as −

left_subtree (keys) ≤ node (key) ≤ right_subtree (keys)


REPRESENTATION
� BST is a collection of nodes arranged in a way where
they maintain BST properties.
� Each node has a key and an associated value.
� In figure below we observe that the root node key (27)
has
⚫ all lower-valued keys on the left sub-tree and
⚫ the higher valued keys on the right sub-tree.
BASIC OPERATIONS ON BINARY SEARCH TREES

� Search − Searches an element in a tree.


� Insert − Inserts an element in a tree.
� Delete − Deletes an element in a tree.
� Pre-order Traversal − Traverses a tree in a pre-
order manner.
� In-order Traversal − Traverses a tree in an in-order
manner.
� Post-order Traversal − Traverses a tree in a post-
order manner.
SEARCH OPERATION

� Whenever an element is to be searched, start


searching from the root node.
� If the data is less than the key value, search for
the element in the left subtree.
� Otherwise, search for the element in the right
subtree.
� Follow the same algorithm for each node.
INSERT OPERATION
� Whenever an element is to be inserted, first
locate its proper location.
� Start searching from the root node, then if the
data is less than the key value, search for the
empty location in the left subtree and insert the
data.
� Otherwise, search for the empty location in the
right subtree and insert the data.
� Examples in notebook
DELETE OPERATION
� In deletion process, there are 4 possible
conditions-
1. Data not present in the tree
2. The node containing data has no child nodes
3. The node containing data has exactly one child
4. The node containing data has exactly two children

� Case-1
⚫ Print the message “Data required is not present”
� Case-2
⚫ Free the memory occupied by the node to be deleted
⚫ Either left or right link of parent node(where node to
be deleted is attached) is set to NULL
CONTD..
� Case-3
⚫ Adjust the pointer of the parent of the node to be
deleted such that after deletion it points to the child
of the node

� Case-4
⚫ The inorder successor of the node to be deleted
occupies its place and is deleted from its original
location
FUNCTION TO INSERT IN BINARY SEARCH TREE
void insert(struct btreenode*, int num)
{
struct node *new= malloc(sizeof (struct node));
new->left=NULL;
new->data=num;
new->right=NULL;

if(root==NULL)
root=new;
else
{
if(num<root)
insert(root->left, num)
else
insert(root->right, num)
}
}
FUNCTION TO DELETE A NODE IN BINARY SEARCH
TREE
void delete(struct btreenode*, int num)
{
struct btreenode *parent, *x, *xsucc;
if(root==NULL)
printf(“Tree is empty”);
else
search(int num);

//If the node to be deleted has no child


if(x->left==NULL && x->right==NULL)
{
if(parent->right==x)
parent->right==NULL;
else
parent->left==NULL;
free(x);
}
//If the node to be deleted has one child node
if(x->left!=NULL && x->right==NULL)
{
if(parent->right==x)
parent->right==x->left;
else
parent->left==x->left;
free(x);
}
if(x->left==NULL && x->right!=NULL)
{
if(parent->right==x)
parent->right==x->right;
else
parent->left==x->right;
free(x);
}
//If the node to be deleted has two children
if(x->left!=NULL && x->right!=NULL)
{
parent=x;
xsucc=x->right;
while(x->left!=NULL)
{
parent=xsucc;
xsucc=xsucc->left;
}
x->data=xsucc->data
free(xsucc);
}
FUNCTION TO SEARCH BINARY SEARCH TREE
Void search(struct btreenode*, int num)
{
struct btreenode *q;
q=root;
while(q!=NULL)
{
if(q->data=num)
{
*x=q;
return;
}
else
{
id(q->data >num)
q=q->left;
else
q=q->right;
}
}
}
THREADED BINARY TREES
� When a binary tree is represented using linked
list representation, the reference part of the node
which doesn't have a child is filled with NULL
pointer.
� In any binary tree linked list representation,
there are more number of NULL pointers than
actual pointers.
� Generally, in any binary tree linked list
representation, if there are 2N number of
reference fields, then N+1 number of reference
fields are filled with NULL ( N+1 are NULL out
of 2N ).
� This NULL pointer does not play any role except
� Threaded Binary Tree", makes use of NULL pointers
to improve its traversal process. In threaded binary
tree, NULL pointers are replaced by references of
other nodes in the tree.
� These extra references are called as threads.
� The idea is to make all left child pointers that are
NULL (in Linked list representation) points to its in-
order predecessor, and all right child pointers that
are NULL (in Linked list representation) points to its
in-order successor.
� If there is no in-order predecessor or in-order
successor, then it points to the root node.
� Consider the following binary tree...

� To convert the above example binary tree into


threaded binary tree, first find the in-order traversal
of that tree...
� In-order traversal of above binary tree...
H-D-I-B-E-A-F-J-C-G

� When we represent the above binary tree using
linked list representation, nodes H, I, E, F,
J and G left child pointers are NULL.
� This NULL is replaced by address of its in-order
predecessor respectively (I to D, E to B, F to A, J
to F and G to C),
� But here the node H does not have its in-order
predecessor, so it points to the root node A.
� Nodes H, I, E, J and G right child pointers are
NULL.
� This NULL pointers are replaced by address of its
in-order successor respectively (H to D, I to B, E to
A, and J to C),
� But here the node G does not have its in-order
successor, so it points to the root node A.
� Above example binary tree is converted into
threaded binary tree as follows.
THREADED BINARY TREE
LINKED REPRESENTATION
EXPRESSION TREES
� Expression tree is a binary tree in which
⚫ each internal node corresponds to operator and
⚫ each leaf node corresponds to operand

� Example – Expression-> 3 + ((5+9)*2)


CONSTRUCTION OF EXPRESSION TREE
� Calculate postfix of the given expression
� If character is operand push that into stack
� If character is operator pop two values from stack
make them its child and push current node again.
� At the end only element of stack will be root of
expression tree.
� Inorder traversal of expression tree produces infix
version of the expression
� Post order traversal of expression tree produces
postfix version
� Preorder traversal of expression tree produces prefix
version
� Construct expression tree for the following-
⚫ a+b-e*f*g
HEIGHT BALANCED TREES (AVL TREES)
� If the input to binary search tree comes in a sorted
(ascending or descending) manner the tree will then
look either left aligned or right aligned (unbalanced)
� AVL tree is a self-balancing Binary Search Tree
(BST) where the difference between heights of left
and right subtrees cannot be more than one for all
nodes.
� This difference is called the Balance Factor.
� BalanceFactor = height(left-sutree) − height(right-
sutree)
� If the difference in the height of left and right sub-
trees is more than 1, the tree is balanced using some
rotation techniques.
AVL ROTATIONS
� To balance itself, an AVL tree may perform the
following four kinds of rotations −
� Left rotation
� Right rotation
� Left-Right rotation
� Right-Left rotation
� The first two rotations are single rotations and
the next two rotations are double rotations.
� To have an unbalanced tree, we at least need a
tree of height 2.
LEFT ROTATION
� If a tree becomes unbalanced, when a node is inserted into the
right subtree of the right subtree, then we perform a single left
rotation −

� Node A has become unbalanced as a node is inserted in the right


subtree of A's right subtree.
� We perform the left rotation by making A the left-subtree of B.
RIGHT ROTATION

� AVL tree may become unbalanced, if a node is


inserted in the left subtree of the left subtree.
The tree then needs a right rotation.

� the unbalanced node becomes the right child of


its left child by performing a right rotation.
LEFT-RIGHT ROTATION

� A left-right rotation is a combination of left rotation


followed by right rotation.
� A node has been inserted into the right subtree of the
left subtree.
� This makes C an unbalanced node.
� These scenarios cause AVL tree to perform left-right
rotation.
1 2

We first perform the left Node C is still unbalanced,


rotation on the left subtree however now, it is because of
of C. This makes A, the left the left-subtree of the left-
subtree of B. subtree.

3 4

We shall now right-rotate the tree, The tree is now


making B the new root node of this balanced.
subtree. C now becomes the right
subtree of its own left subtree.
RIGHT-LEFT ROTATION
� The second type of double rotation is Right-Left
Rotation.
� It is a combination of right rotation followed by
left rotation.
� A node has been inserted into the left subtree of
the right subtree. This makes A, an unbalanced
node with balance factor 2.
First, we perform the right rotation
along C node, making C the right Node A is still unbalanced because
subtree of its own left subtree B. of the right subtree of its right
Now, B becomes the right subtree subtree and requires a left
of A. rotation.

A left rotation is performed by


The tree is now
making B the new root node of the
balanced.
subtree. A becomes the left subtree of its
right subtree B.
AVL
� Examples solved in notebook

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy