SlideShare ist ein Scribd-Unternehmen logo
1 von 39
Chapter Six
Tree Data Structure
Introduction
• Linear data structures
– Forms a sequence. E.g., list, stack and queue
– Each element has a unique successor & a unique predecessor
– two basic ways of representing linear structures in memory
• relationship between the elements by means of pointers
(links)
• using sequential organization, that is, arrays
• Non-linear data structures
– Used to represent the data containing hierarchical or
network relationship between the elements. E.g., tree and graph
– Each element may have more than one predecessor as well as
successor
– capable of expressing more complex relationships than linear
data structures
Introduction
Folder and subfolders organization
Definition of General Tree
• A tree T is defined recursively as follows:
A set of zero items is a tree, called the empty tree
(or null tree).
The collection can be empty or consists of a node
called root, R, and zero or more non-empty (sub)
trees T1, T2, …, Tn.
Basic Terminology
Root: The root node is the topmost node in the tree
hierarchy. In other words, the root node is the one that
doesn't have any parent.
Root: the unique (beginning) vertex in a rooted tree.
e.g., b
Descendant: The immediate successor of the given
node is known as a descendant of a node.
e.g., m,n,h and i are descendants of e or b;
Child node: If the node is a descendant of any node,
then the node is known as a child node.
e.g., c,d,e and f are children of b;
j,k and l are children of f
Edge: refers to a directed/undirected edge from a
parent to its child
Parent − Any node except the root node has one edge
upward to a node called parent.
Parent: the root vertex is considered as parent of children
e.g., b is parent of c,d,e anf f; k is parent of o,p and q
Siblings: The nodes that have the same parent are known as
siblings.
e.g., c,d,e and f are siblings; j,k and l are siblings
Basic Terminology
Leaves(terminal or external nodes): The node of the
tree, which doesn't have any child node
e.g., c,g,m,n,j,….
Internal nodes/vertex:
A node has at least one child node or non-leaf node.
e.g., d,e,k,f…
The degree of a node: is the number of subtrees it has.
The degree of a tree is the maximum degree of a node
in the tree. The degree of each leaf node is zero.
e.g., the above tree has degree 4; k has degree 3
Number of edges: If there are n nodes, then there
would n-1 edges.
Basic Terminology
Ancestor node:- An ancestor of a node is any predecessor
node on a path from the root to that node.
e.g., b,f and k are ancestors of o,p and q
Path: each node can be reached from the root through a unique
sequence of nodes called path.
The length of a path is the number of edges it contains
(which is one less than the number of nodes on the path).
The depth or level of a node: is the length of a node, which is
the length of a directed path from the root. e.g., depth of n is 3
 The root node has 0 depth.
NB: The depth of a tree is equal to the depth of the deepest
leaf;
this is always equal to the height of the tree.
The height of a tree is given by the height of its root node.
Height of node x: The height of node x can be defined as the
longest path from the node x to the leaf node.
The height of a vertex/node: is the length of the longest path
from that node to a leaf that is a descendent of the node.
e.g., the height of d is 1;
height of b is 3;
all leaves are at height 0.
At each level of i, the maximum number of nodes is 2i.
Binary tree
• The Binary tree means that the node can have at most two
children. means each vertex in the tree has no children,
one child, or two children.
• If a vertex has two children, the first child is referred to as
the left child, and the second child is referred to as the right
child.
• If a vertex has only a single child, then that child may be
positioned as either a left child or a right child.
Types of Binary Tree
Full/ proper/ strict Binary tree
• A binary tree is a full binary if every nodes in a tree
either has two children or no child at all.
• The number of leaves in a full binary tree is always
one more than the number of internal vertices in the
tree.
• A perfect (or balanced) binary tree: is a full
binary tree in which all leaves have the same depth.
• It is easy to show that the number of vertices in a
perfect binary tree is always 2h+1 -1 considering the
root at level 0 and a tree of height h.
• Complete Binary Tree:- in which the length from the
root to any leaf node is either h or h-1. where h is
height of the tree.
• The complete binary tree is a tree in which all the
nodesare completely filled except the last level.
• In a complete binary tree, the nodes should be added
from the left.
Representation of a binary tree
• Each node in the binary tree contains one or more data
fields, and two pointers: one to the left child and the other
to the right child.
struct node {
Data field declarations;
node *left; // pointer to left child;
node *right; // pointer to right child;
};
node *RootPtr=NULL; /* root is external pointer that
holds the address of the root node permanently.*/
Representation of a binary tree
Left data right
Left data right Left data right
Left data right Left data right
Left data right
NULL NULL
NULL NULL NULL
NULL
NULL
RootPtr
Constructing an Expression tree
• An expression tree is a binary tree that stores values on leaf nodes
and operators on internal nodes.
Consider the expression in RPN: A B – C E F - * +
• Then we would perform the following.
1. Push A and B into stack ( a pointer to each of these nodes are put in the
stack)
2. Next, the binary operator (-) is read; pop A & B and build a tree; push the
tree (i.e. pointer to its root) into stack.
3. Push C, E, & F into stack (they are operands)
4. Next a (-) is read, so two pointers to E & F are popped, a new tree is
formed, & a pointer to it is pushed into stack.
5. Next, a (*) is read, so two pointers to C and subtree (on top) are popped
and a new tree is formed, & a pointer to it is pushed into stack.
6. Finally, the last symbol (+) is read, so two pointers to subtrees are popped,
a new tree is formed, and a pointer to this tree is left on stack.
Constructing an Expression tree
• The following is the resulting expression tree.
A B – C E F - * +
Tree traversal
• Is the process of visiting each node in a tree exactly
once.
• We consider three methods for traversing a binary
tree.
– Preorder traversal
– Inorder traversal
– Postorder traversal
Tree traversal
• Preorder traversal: The nodes will be visited in the
following order.
– First process the root node.
– Then recursively visit all nodes in the left subtree;
– Finally, recursively visit all nodes in the right subtree.
Preorder traversal: 20, 12, 10, 16, 14, 26, 24, 22, 30, 28,
32
C++ implementation
void Preorder (Node *Rootnode) {
if(Rootnode ! = NULL){
cout<< Rootnode->Num;
Preorder(Rootnode->Left);
Preorder(Rootnode->Right);
} }
Tree traversal
• Inorder traversal: The nodes will be visited in the
following order.
– First recursively visit all nodes in the left subtree
– Then process the root node.
– Finally, recursively visit all nodes in the right subtree
Inorder traversal: 10, 12, 14, 16, 20, 22, 24, 26, 28, 30,
32
Used to display nodes in ascending order from a BST.
C++ implementation
void Inorder (Node *Rootnode) {
if(Rootnode ! = NULL){
Inorder(Rootnode->Left);
cout<< Rootnode->Num;
Inorder(Rootnode->Right);
} }
Tree traversal
• Postorder traversal: The nodes will be visited in the
following order.
– First recursively visit all nodes in the left subtree
– Then recursively visit all nodes in the right subtree
– Finally, process the root node
Postorder traversal: 10, 14, 16, 12, 22, 24, 28, 32, 30, 26, 20
C++ implementation
void Postorder (Node *Rootnode) {
if(Rootnode ! = NULL){
Postorder(Rootnode->Left);
Postorder(Rootnode->Right);
cout<< Rootnode->Num;
// or any operation on the node
}
}
Tree traversal
• A binary tree traversal can also be applied to generate
mathematical expression in infix, prefix, and postfix notation
from an expression tree.
– Preorder traversal: - used to generate prefix notation.
– Inorder traversal: - used to generate infix notation.
– Postorder traversal: - used to generate postfix notation.
Preorder traversal → prefix notation
+ – A * B C + D / E F
Inorder traversal → infix notation
A – B * C + D + E / F
Postorder traversal → postfix notation
A B C * – D E F / + +
Binary Search Tree – BST
• Trees can be used for sorting and searching data
• Search trees: general trees used for the purpose of searching
and sorting
• Binary search trees: binary trees used for the purpose of
searching and sorting
• A binary tree is a search tree if it is empty, or satisfies the
following:
– Every node has a key value that uniquely identifies it (i.e.
no two nodes have the same key)
– For every node, N, in the tree, the values of all the items in
its left subtree are smaller than the value in N, and the
values of all the items in its right subtree are larger than
the value in N.
Binary Search Tree – BST
Operations on Binary Search Tree
• The following are basic operations in binary search tree
– Findmin(tree) and Findmax(tree) – finds and returns the
position (or node) of the smallest and largest elements in the
tree, respectively.
– Insert (tree, x)- finds the appropriate position and inserts a
new node containing the key value x.
– Search (tree, x)-returns a pointer to the node in the tree that
has key value x, or NULL if there is no such key.
– Delete (tree, x) – finds the node containing x in the tree and
removes that node.
• Note that when a node is inserted or deleted from BST,
the definition of binary search tree should be preserved
C++ Implementation of Findmin and Findmax
node* findmax(node *T)
{
if (T!=NULL)
while(T->right!=NULL)
T=T->right;
return T;
}
node* findmin(node *T)
{
if (T!=NULL)
while (T->left!=NULL)
T=T->left;
return T;
}
Insertion in BST
• Suppose there is a binary search tree whose root node is
pointed to by RootPtr and we want to insert a node
(that stores x) pointed by NewNode. There are two
cases:
Case 1: There is no data in the tree (i.e. RootPtr is
NULL)
– The node pointed by NewNode should be made the
root node.
Case 2: There is data (i.e. RootPtr is NULL)
– Search the appropriate position, and insert the node
in that position.
Create the binary search tree using the following data elements
43, 10, 79, 90, 12, 54, 11, 9, 50
Insert 43 into the tree as the root of the tree.
Read the next element, if it is lesser than the root node element,
insert it as the root of the left sub-tree.
Otherwise, insert it as the root of the right of the right sub-tree.
• The process of creating BST by using the given elements, is
shown in the next slide.
C++ Implementation insertion
void InsertBST(node *RNP, node *INP)
{//RNP=RootPtr and INP=NewNode
int Inserted=0;
while(Inserted = =0)
{
if(RNP->Num > INP->Num)
{
if(RNP->Left = = NULL)
{
RNP->Left = INP;
Inserted=1;
}
else
RNP = RNP->Left;
}
else
{
if(RNP->Right = = NULL)
{
RNP->Right = INP;
Inserted=1;
}
else
RNP = RNP->Right;
}
}//end of while
}
A recursive version of the function can
also be given as follows.
void InsertBST(node *RNP, node *INP)
{
if(RNP->Num>INP->Num)
{
if(RNP->Left==NULL)
RNP->Left = INP;
else
InsertBST(RNP->Left, INP);
}
else
{
if(RNP->Right==NULL)
RNP->Right = INP;
else
InsertBST(RNP->Right, INP);
}
}
Searching in BST
• To search a node (whose key value is x) in a binary
search tree (whose root node is pointed by RootPtr),
the following function return a pointer that points to
the node containing the element searched, or NULL
pointer if not found.
node *SearchBST (node *RootPtr, int x)
{
if((RootPtr = = NULL) || (RootPtr->Num = = x))
return(RootPtr);
else if(RootPtr->Num > x)
return(SearchBST(RootPtr->Left, x));
else
return(SearchBST (RootPtr->Right, x));
}
Deletion from a BST
• An algorithm for deleting a node from a binary search tree in such a way
that the remaining nodes still have the same inorder traversal:
– Leaves - these are the easiest, since all we need to do is delete the leaf and
set the pointer from its parent (if any) to NULL.
– Nodes with a single child - these too are fairly easy, since we just redirect
the pointer from the node's parent so that it points to the child.
– Nodes with both children - these can be fairly tricky, since we must
rearrange the tree to some extent. The method we shall use is to replace the
node being deleted by the rightmost node in its left sub tree. (We could
equally well have used the leftmost node in the right sub tree.) Because of
the rules for inorder traversals, this method guarantees the same traversal.
• Assuming the node to be deleted is present in the tree, we are faced with
two possibilities:
– the required node is the root node, or
– it is some other node.
• These must be treated as separate cases, since the root node has no
parent
C++ Implementation of node deletion
void DeleteBST (node *T, int x)
{ node *temp;
if (T==NULL)
cout<<” data not found…”;
else if (x<T->item)
T->left = DeleteBST (T->left, x);
else if (x>T->item)
T->right = DeleteBST (T->right, x);
else //node to be deleted found
{
if (T->left!=NULL && T->right!=NULL) //node having two children
{
temp = Findmin( T->right); //finds the smallest to the right of the node to be deleted.
T->item = temp->item; //copying smallest value to the node to be deleted
T->right = DeleteBST (T->right, T->item); //deletes the node containing smallest value.
}
else //one or zero child
{ temp = T;
if (T->left == NULL)
T = T->right;
else
if (T->right == NULL)
T = T->left;
delete (temp);
} }}
Sorting using Binary Search Tree
• One way that a binary search tree can be used
to sort data is as follows.
– E.g., Let us suppose that we have a list of integers,
such as 5, 2, 8, 4, and 1, that we wish to sort into
ascending order.
• We can perform a two-stage sorting algorithm.
– The first stage involves inserting the integers into a
binary search tree
– The second stage is performing inorder traversal
Sorting using Binary Search Tree
Stage 2: Inorder traversal - 1, 2, 4, 5, 8,
Stage 1: inserting the elements (5, 2, 8, 4, 1 )into
the BST one by one
Efficiency of Binary Search Trees
• The tree sort and tree search algorithms work well if
the initial data are in a jumbled order, since the binary
search tree will be fairly well balanced, which means
that there are roughly equal numbers of nodes in the
left and right subtree of any node.
• Trees that are wide and shallow have only a few levels,
so the insertion and searching routines have relatively
few steps.
• In fact, in these cases
– the sorting routine is O (n log n)
– the searching routine is essentially a binary search, and so is
O (log n).

Weitere ähnliche Inhalte

Ähnlich wie Tree.pptx

Final tree.ppt tells about tree presentation
Final tree.ppt tells about tree presentationFinal tree.ppt tells about tree presentation
Final tree.ppt tells about tree presentationnakulvarshney371
 
Binary tree
Binary treeBinary tree
Binary treeRajendran
 
Lecture 5 trees
Lecture 5 treesLecture 5 trees
Lecture 5 treesVictor Palmar
 
Farhana shaikh webinar_treesindiscretestructure
Farhana shaikh webinar_treesindiscretestructureFarhana shaikh webinar_treesindiscretestructure
Farhana shaikh webinar_treesindiscretestructureFarhana Shaikh
 
Trees and Graphs in data structures and Algorithms
Trees and Graphs in data structures and AlgorithmsTrees and Graphs in data structures and Algorithms
Trees and Graphs in data structures and AlgorithmsBHARATH KUMAR
 
Introduction to tree ds
Introduction to tree dsIntroduction to tree ds
Introduction to tree dsViji B
 
Tree Introduction.pptx
Tree Introduction.pptxTree Introduction.pptx
Tree Introduction.pptxRahulAI
 
tree-160731205832.pptx
tree-160731205832.pptxtree-160731205832.pptx
tree-160731205832.pptxMouDhara1
 
7 chapter4 trees_binary
7 chapter4 trees_binary7 chapter4 trees_binary
7 chapter4 trees_binarySSE_AndyLi
 
Lecture notes data structures tree
Lecture notes data structures   treeLecture notes data structures   tree
Lecture notes data structures treemaamir farooq
 

Ähnlich wie Tree.pptx (20)

Final tree.ppt tells about tree presentation
Final tree.ppt tells about tree presentationFinal tree.ppt tells about tree presentation
Final tree.ppt tells about tree presentation
 
Unit 5 Tree.pptx
Unit 5 Tree.pptxUnit 5 Tree.pptx
Unit 5 Tree.pptx
 
Binary tree
Binary treeBinary tree
Binary tree
 
Lecture 5 trees
Lecture 5 treesLecture 5 trees
Lecture 5 trees
 
Data structures 3
Data structures 3Data structures 3
Data structures 3
 
Tree
TreeTree
Tree
 
Trees
TreesTrees
Trees
 
Farhana shaikh webinar_treesindiscretestructure
Farhana shaikh webinar_treesindiscretestructureFarhana shaikh webinar_treesindiscretestructure
Farhana shaikh webinar_treesindiscretestructure
 
UNIT-4 TREES.ppt
UNIT-4 TREES.pptUNIT-4 TREES.ppt
UNIT-4 TREES.ppt
 
Trees and Graphs in data structures and Algorithms
Trees and Graphs in data structures and AlgorithmsTrees and Graphs in data structures and Algorithms
Trees and Graphs in data structures and Algorithms
 
Unit 3,4.docx
Unit 3,4.docxUnit 3,4.docx
Unit 3,4.docx
 
tree.ppt
tree.ppttree.ppt
tree.ppt
 
Binary tree
Binary  treeBinary  tree
Binary tree
 
Introduction to tree ds
Introduction to tree dsIntroduction to tree ds
Introduction to tree ds
 
Unit 6 tree
Unit   6 treeUnit   6 tree
Unit 6 tree
 
Tree Introduction.pptx
Tree Introduction.pptxTree Introduction.pptx
Tree Introduction.pptx
 
tree-160731205832.pptx
tree-160731205832.pptxtree-160731205832.pptx
tree-160731205832.pptx
 
Tree 11.ppt
Tree 11.pptTree 11.ppt
Tree 11.ppt
 
7 chapter4 trees_binary
7 chapter4 trees_binary7 chapter4 trees_binary
7 chapter4 trees_binary
 
Lecture notes data structures tree
Lecture notes data structures   treeLecture notes data structures   tree
Lecture notes data structures tree
 

KĂźrzlich hochgeladen

(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingrknatarajan
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoĂŁo Esperancinha
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 

KĂźrzlich hochgeladen (20)

(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 

Tree.pptx

  • 2. Introduction • Linear data structures – Forms a sequence. E.g., list, stack and queue – Each element has a unique successor & a unique predecessor – two basic ways of representing linear structures in memory • relationship between the elements by means of pointers (links) • using sequential organization, that is, arrays • Non-linear data structures – Used to represent the data containing hierarchical or network relationship between the elements. E.g., tree and graph – Each element may have more than one predecessor as well as successor – capable of expressing more complex relationships than linear data structures
  • 4. Definition of General Tree • A tree T is defined recursively as follows: A set of zero items is a tree, called the empty tree (or null tree). The collection can be empty or consists of a node called root, R, and zero or more non-empty (sub) trees T1, T2, …, Tn.
  • 5. Basic Terminology Root: The root node is the topmost node in the tree hierarchy. In other words, the root node is the one that doesn't have any parent. Root: the unique (beginning) vertex in a rooted tree. e.g., b
  • 6. Descendant: The immediate successor of the given node is known as a descendant of a node. e.g., m,n,h and i are descendants of e or b; Child node: If the node is a descendant of any node, then the node is known as a child node. e.g., c,d,e and f are children of b; j,k and l are children of f Edge: refers to a directed/undirected edge from a parent to its child
  • 7. Parent − Any node except the root node has one edge upward to a node called parent. Parent: the root vertex is considered as parent of children e.g., b is parent of c,d,e anf f; k is parent of o,p and q Siblings: The nodes that have the same parent are known as siblings. e.g., c,d,e and f are siblings; j,k and l are siblings
  • 8. Basic Terminology Leaves(terminal or external nodes): The node of the tree, which doesn't have any child node e.g., c,g,m,n,j,…. Internal nodes/vertex: A node has at least one child node or non-leaf node. e.g., d,e,k,f…
  • 9. The degree of a node: is the number of subtrees it has. The degree of a tree is the maximum degree of a node in the tree. The degree of each leaf node is zero. e.g., the above tree has degree 4; k has degree 3 Number of edges: If there are n nodes, then there would n-1 edges.
  • 10. Basic Terminology Ancestor node:- An ancestor of a node is any predecessor node on a path from the root to that node. e.g., b,f and k are ancestors of o,p and q Path: each node can be reached from the root through a unique sequence of nodes called path. The length of a path is the number of edges it contains (which is one less than the number of nodes on the path).
  • 11. The depth or level of a node: is the length of a node, which is the length of a directed path from the root. e.g., depth of n is 3  The root node has 0 depth. NB: The depth of a tree is equal to the depth of the deepest leaf; this is always equal to the height of the tree. The height of a tree is given by the height of its root node.
  • 12. Height of node x: The height of node x can be defined as the longest path from the node x to the leaf node. The height of a vertex/node: is the length of the longest path from that node to a leaf that is a descendent of the node. e.g., the height of d is 1; height of b is 3; all leaves are at height 0. At each level of i, the maximum number of nodes is 2i.
  • 13. Binary tree • The Binary tree means that the node can have at most two children. means each vertex in the tree has no children, one child, or two children. • If a vertex has two children, the first child is referred to as the left child, and the second child is referred to as the right child. • If a vertex has only a single child, then that child may be positioned as either a left child or a right child.
  • 14. Types of Binary Tree Full/ proper/ strict Binary tree • A binary tree is a full binary if every nodes in a tree either has two children or no child at all. • The number of leaves in a full binary tree is always one more than the number of internal vertices in the tree.
  • 15. • A perfect (or balanced) binary tree: is a full binary tree in which all leaves have the same depth. • It is easy to show that the number of vertices in a perfect binary tree is always 2h+1 -1 considering the root at level 0 and a tree of height h.
  • 16. • Complete Binary Tree:- in which the length from the root to any leaf node is either h or h-1. where h is height of the tree. • The complete binary tree is a tree in which all the nodesare completely filled except the last level. • In a complete binary tree, the nodes should be added from the left.
  • 17. Representation of a binary tree • Each node in the binary tree contains one or more data fields, and two pointers: one to the left child and the other to the right child. struct node { Data field declarations; node *left; // pointer to left child; node *right; // pointer to right child; }; node *RootPtr=NULL; /* root is external pointer that holds the address of the root node permanently.*/
  • 18. Representation of a binary tree Left data right Left data right Left data right Left data right Left data right Left data right NULL NULL NULL NULL NULL NULL NULL RootPtr
  • 19. Constructing an Expression tree • An expression tree is a binary tree that stores values on leaf nodes and operators on internal nodes. Consider the expression in RPN: A B – C E F - * + • Then we would perform the following. 1. Push A and B into stack ( a pointer to each of these nodes are put in the stack) 2. Next, the binary operator (-) is read; pop A & B and build a tree; push the tree (i.e. pointer to its root) into stack. 3. Push C, E, & F into stack (they are operands) 4. Next a (-) is read, so two pointers to E & F are popped, a new tree is formed, & a pointer to it is pushed into stack. 5. Next, a (*) is read, so two pointers to C and subtree (on top) are popped and a new tree is formed, & a pointer to it is pushed into stack. 6. Finally, the last symbol (+) is read, so two pointers to subtrees are popped, a new tree is formed, and a pointer to this tree is left on stack.
  • 20. Constructing an Expression tree • The following is the resulting expression tree. A B – C E F - * +
  • 21. Tree traversal • Is the process of visiting each node in a tree exactly once. • We consider three methods for traversing a binary tree. – Preorder traversal – Inorder traversal – Postorder traversal
  • 22. Tree traversal • Preorder traversal: The nodes will be visited in the following order. – First process the root node. – Then recursively visit all nodes in the left subtree; – Finally, recursively visit all nodes in the right subtree. Preorder traversal: 20, 12, 10, 16, 14, 26, 24, 22, 30, 28, 32 C++ implementation void Preorder (Node *Rootnode) { if(Rootnode ! = NULL){ cout<< Rootnode->Num; Preorder(Rootnode->Left); Preorder(Rootnode->Right); } }
  • 23. Tree traversal • Inorder traversal: The nodes will be visited in the following order. – First recursively visit all nodes in the left subtree – Then process the root node. – Finally, recursively visit all nodes in the right subtree Inorder traversal: 10, 12, 14, 16, 20, 22, 24, 26, 28, 30, 32 Used to display nodes in ascending order from a BST. C++ implementation void Inorder (Node *Rootnode) { if(Rootnode ! = NULL){ Inorder(Rootnode->Left); cout<< Rootnode->Num; Inorder(Rootnode->Right); } }
  • 24. Tree traversal • Postorder traversal: The nodes will be visited in the following order. – First recursively visit all nodes in the left subtree – Then recursively visit all nodes in the right subtree – Finally, process the root node Postorder traversal: 10, 14, 16, 12, 22, 24, 28, 32, 30, 26, 20 C++ implementation void Postorder (Node *Rootnode) { if(Rootnode ! = NULL){ Postorder(Rootnode->Left); Postorder(Rootnode->Right); cout<< Rootnode->Num; // or any operation on the node } }
  • 25. Tree traversal • A binary tree traversal can also be applied to generate mathematical expression in infix, prefix, and postfix notation from an expression tree. – Preorder traversal: - used to generate prefix notation. – Inorder traversal: - used to generate infix notation. – Postorder traversal: - used to generate postfix notation. Preorder traversal → prefix notation + – A * B C + D / E F Inorder traversal → infix notation A – B * C + D + E / F Postorder traversal → postfix notation A B C * – D E F / + +
  • 26. Binary Search Tree – BST • Trees can be used for sorting and searching data • Search trees: general trees used for the purpose of searching and sorting • Binary search trees: binary trees used for the purpose of searching and sorting • A binary tree is a search tree if it is empty, or satisfies the following: – Every node has a key value that uniquely identifies it (i.e. no two nodes have the same key) – For every node, N, in the tree, the values of all the items in its left subtree are smaller than the value in N, and the values of all the items in its right subtree are larger than the value in N.
  • 27. Binary Search Tree – BST
  • 28. Operations on Binary Search Tree • The following are basic operations in binary search tree – Findmin(tree) and Findmax(tree) – finds and returns the position (or node) of the smallest and largest elements in the tree, respectively. – Insert (tree, x)- finds the appropriate position and inserts a new node containing the key value x. – Search (tree, x)-returns a pointer to the node in the tree that has key value x, or NULL if there is no such key. – Delete (tree, x) – finds the node containing x in the tree and removes that node. • Note that when a node is inserted or deleted from BST, the definition of binary search tree should be preserved
  • 29. C++ Implementation of Findmin and Findmax node* findmax(node *T) { if (T!=NULL) while(T->right!=NULL) T=T->right; return T; } node* findmin(node *T) { if (T!=NULL) while (T->left!=NULL) T=T->left; return T; }
  • 30. Insertion in BST • Suppose there is a binary search tree whose root node is pointed to by RootPtr and we want to insert a node (that stores x) pointed by NewNode. There are two cases: Case 1: There is no data in the tree (i.e. RootPtr is NULL) – The node pointed by NewNode should be made the root node. Case 2: There is data (i.e. RootPtr is NULL) – Search the appropriate position, and insert the node in that position.
  • 31. Create the binary search tree using the following data elements 43, 10, 79, 90, 12, 54, 11, 9, 50 Insert 43 into the tree as the root of the tree. Read the next element, if it is lesser than the root node element, insert it as the root of the left sub-tree. Otherwise, insert it as the root of the right of the right sub-tree. • The process of creating BST by using the given elements, is shown in the next slide.
  • 32.
  • 33. C++ Implementation insertion void InsertBST(node *RNP, node *INP) {//RNP=RootPtr and INP=NewNode int Inserted=0; while(Inserted = =0) { if(RNP->Num > INP->Num) { if(RNP->Left = = NULL) { RNP->Left = INP; Inserted=1; } else RNP = RNP->Left; } else { if(RNP->Right = = NULL) { RNP->Right = INP; Inserted=1; } else RNP = RNP->Right; } }//end of while } A recursive version of the function can also be given as follows. void InsertBST(node *RNP, node *INP) { if(RNP->Num>INP->Num) { if(RNP->Left==NULL) RNP->Left = INP; else InsertBST(RNP->Left, INP); } else { if(RNP->Right==NULL) RNP->Right = INP; else InsertBST(RNP->Right, INP); } }
  • 34. Searching in BST • To search a node (whose key value is x) in a binary search tree (whose root node is pointed by RootPtr), the following function return a pointer that points to the node containing the element searched, or NULL pointer if not found. node *SearchBST (node *RootPtr, int x) { if((RootPtr = = NULL) || (RootPtr->Num = = x)) return(RootPtr); else if(RootPtr->Num > x) return(SearchBST(RootPtr->Left, x)); else return(SearchBST (RootPtr->Right, x)); }
  • 35. Deletion from a BST • An algorithm for deleting a node from a binary search tree in such a way that the remaining nodes still have the same inorder traversal: – Leaves - these are the easiest, since all we need to do is delete the leaf and set the pointer from its parent (if any) to NULL. – Nodes with a single child - these too are fairly easy, since we just redirect the pointer from the node's parent so that it points to the child. – Nodes with both children - these can be fairly tricky, since we must rearrange the tree to some extent. The method we shall use is to replace the node being deleted by the rightmost node in its left sub tree. (We could equally well have used the leftmost node in the right sub tree.) Because of the rules for inorder traversals, this method guarantees the same traversal. • Assuming the node to be deleted is present in the tree, we are faced with two possibilities: – the required node is the root node, or – it is some other node. • These must be treated as separate cases, since the root node has no parent
  • 36. C++ Implementation of node deletion void DeleteBST (node *T, int x) { node *temp; if (T==NULL) cout<<” data not found…”; else if (x<T->item) T->left = DeleteBST (T->left, x); else if (x>T->item) T->right = DeleteBST (T->right, x); else //node to be deleted found { if (T->left!=NULL && T->right!=NULL) //node having two children { temp = Findmin( T->right); //finds the smallest to the right of the node to be deleted. T->item = temp->item; //copying smallest value to the node to be deleted T->right = DeleteBST (T->right, T->item); //deletes the node containing smallest value. } else //one or zero child { temp = T; if (T->left == NULL) T = T->right; else if (T->right == NULL) T = T->left; delete (temp); } }}
  • 37. Sorting using Binary Search Tree • One way that a binary search tree can be used to sort data is as follows. – E.g., Let us suppose that we have a list of integers, such as 5, 2, 8, 4, and 1, that we wish to sort into ascending order. • We can perform a two-stage sorting algorithm. – The first stage involves inserting the integers into a binary search tree – The second stage is performing inorder traversal
  • 38. Sorting using Binary Search Tree Stage 2: Inorder traversal - 1, 2, 4, 5, 8, Stage 1: inserting the elements (5, 2, 8, 4, 1 )into the BST one by one
  • 39. Efficiency of Binary Search Trees • The tree sort and tree search algorithms work well if the initial data are in a jumbled order, since the binary search tree will be fairly well balanced, which means that there are roughly equal numbers of nodes in the left and right subtree of any node. • Trees that are wide and shallow have only a few levels, so the insertion and searching routines have relatively few steps. • In fact, in these cases – the sorting routine is O (n log n) – the searching routine is essentially a binary search, and so is O (log n).

Hinweis der Redaktion

  1. Node(vertex) : an element in the tree, it maybe labeled or not. e.g., b, e, g, …