SlideShare uma empresa Scribd logo
1 de 34
1
Tree Traversal Techniques; Heaps
•Tree Traversal Concept
•Tree Traversal Techniques: Preorder,
Inorder, Postorder
•Full Trees
•Almost Complete Trees
•Heaps
2
Binary-Tree Related Definitions
• The children of any node in a binary tree are
ordered into a left child and a right child
• A node can have a left and
a right child, a left child
only, a right child only,
or no children
• The tree made up of a left
child (of a node x) and all its
descendents is called the left subtree of x
• Right subtrees are defined similarly
10
1
3
11
98
4 6
5
7
12
3
A Binary-tree Node Class
class TreeNode {
public:
typedef int datatype;
TreeNode(datatype x=0, TreeNode *left=NULL,
TreeNode *right=NULL){
data=x; this->left=left; this->right=right; };
datatype getData( ) {return data;};
TreeNode *getLeft( ) {return left;};
TreeNode *getRight( ) {return right;};
void setData(datatype x) {data=x;};
void setLeft(TreeNode *ptr) {left=ptr;};
void setRight(TreeNode *ptr) {right=ptr;};
private:
datatype data; // different data type for other apps
TreeNode *left; // the pointer to left child
TreeNode *right; // the pointer to right child
};
4
Binary Tree Class
class Tree {
public:
typedef int datatype;
Tree(TreeNode *rootPtr=NULL){this->rootPtr=rootPtr;};
TreeNode *search(datatype x);
bool insert(datatype x); TreeNode * remove(datatype x);
TreeNode *getRoot(){return rootPtr;};
Tree *getLeftSubtree(); Tree *getRightSubtree();
bool isEmpty(){return rootPtr == NULL;};
private:
TreeNode *rootPtr;
};
5
Binary Tree Traversal
• Traversal is the process of visiting every node once
• Visiting a node entails doing some processing at that node, but when
describing a traversal strategy, we need not concern ourselves with
what that processing is
6
Binary Tree Traversal Techniques
• Three recursive techniques for binary tree traversal
• In each technique, the left subtree is traversed recursively, the right
subtree is traversed recursively, and the root is visited
• What distinguishes the techniques from one another is the order of
those 3 tasks
7
Preoder, Inorder, Postorder
• In Preorder, the root
is visited before (pre)
the subtrees traversals
• In Inorder, the root is
visited in-between left
and right subtree traversal
• In Preorder, the root
is visited after (pre)
the subtrees traversals
Preorder Traversal:
1. Visit the root
2. Traverse left subtree
3. Traverse right subtree
Inorder Traversal:
1. Traverse left subtree
2. Visit the root
3. Traverse right subtree
Postorder Traversal:
1. Traverse left subtree
2. Traverse right subtree
3. Visit the root
8
Illustrations for Traversals
• Assume: visiting a node
is printing its label
• Preorder:
1 3 5 4 6 7 8 9 10 11 12
• Inorder:
4 5 6 3 1 8 7 9 11 10 12
• Postorder:
4 6 5 3 8 11 12 10 9 7 1
1
3
11
98
4 6
5
7
12
10
9
Illustrations for Traversals (Contd.)
• Assume: visiting a node
is printing its data
• Preorder: 15 8 2 6 3 7
11 10 12 14 20 27 22 30
• Inorder: 2 3 6 7 8 10 11
12 14 15 20 22 27 30
• Postorder: 3 7 6 2 10 14
12 11 8 22 30 27 20 15
6
15
8
2
3 7
11
10
14
12
20
27
22 30
10
Code for the Traversal Techniques
• The code for visit
is up to you to
provide, depending
on the application
• A typical example
for visit(…) is to
print out the data
part of its input
node
void inOrder(Tree *tree){
if (tree->isEmpty( )) return;
inOrder(tree->getLeftSubtree( ));
visit(tree->getRoot( ));
inOrder(tree->getRightSubtree( ));
}
void preOrder(Tree *tree){
if (tree->isEmpty( )) return;
visit(tree->getRoot( ));
preOrder(tree->getLeftSubtree());
preOrder(tree->getRightSubtree());
}
void postOrder(Tree *tree){
if (tree->isEmpty( )) return;
postOrder(tree->getLeftSubtree( ));
postOrder(tree->getRightSubtree( ));
visit(tree->getRoot( ));
}
11
Application of Traversal Sorting a BST
• Observe the output of the inorder traversal of
the BST example two slides earlier
• It is sorted
• This is no coincidence
• As a general rule, if you output the keys (data)
of the nodes of a BST using inorder traversal,
the data comes out sorted in increasing order
12
Other Kinds of Binary Trees
(Full Binary Trees)
• Full Binary Tree: A full binary tree is a binary tree
where all the leaves are on the same level and
every non-leaf has two children
• The first four full binary trees are:
13
Examples of Non-Full Binary Trees
• These trees are NOT full binary trees: (do you
know why?)
14
Canonical Labeling of
Full Binary Trees
• Label the nodes from 1 to n from the top to the
bottom, left to right
1 1
2 3
1
2 3
4 5 6 7
1
2 3
4
5 6 7
8 9 10 11
12 13 14 15
Relationships between labels
of children and parent:
2i 2i+1
i
15
Other Kinds of Binary Trees
(Almost Complete Binary trees)
• Almost Complete Binary Tree: An almost
complete binary tree of n nodes, for any arbitrary
nonnegative integer n, is the binary tree made up
of the first n nodes of a canonically labeled full
binary
1
1
2
1
2 3
4 5 6 7
1
2
1
2 3
4 5 6
1
2 3
4
1
2 3
4 5
16
Depth/Height of Full Trees and Almost Complete
Trees
• The height (or depth ) h of such trees is O(log n)
• Proof: In the case of full trees,
• The number of nodes n is: n=1+2+22+23+…+2h=2h+1-1
• Therefore, 2h+1 = n+1, and thus, h=log(n+1)-1
• Hence, h=O(log n)
• For almost complete trees, the proof is left as an exercise.
17
Canonical Labeling of
Almost Complete Binary Trees
• Same labeling inherited from full binary trees
• Same relationship holding between the labels of
children and parents:
Relationships between labels
of children and parent:
2i 2i+1
i
18
Array Representation of Full Trees and Almost
Complete Trees
• A canonically label-able tree, like full binary trees and almost
complete binary trees, can be represented by an array A of the same
length as the number of nodes
• A[k] is identified with node of label k
• That is, A[k] holds the data of node k
• Advantage:
• no need to store left and right pointers in the nodes  save memory
• Direct access to nodes: to get to node k, access A[k]
19
Illustration of Array Representation
• Notice: Left child of A[5] (of data 11) is A[2*5]=A[10] (of data 18), and
its right child is A[2*5+1]=A[11] (of data 12).
• Parent of A[4] is A[4/2]=A[2], and parent of A[5]=A[5/2]=A[2]
6
15
8
2 11
18 12
20
27
13
30
15 8 20 2 11 30 27 13 6 10 12
1 2 3 4 5 6 7 8 9 10 11
20
Adjustment of Indexes
• Notice that in the previous slides, the node labels start from 1, and so
would the corresponding arrays
• But in C/C++, array indices start from 0
• The best way to handle the mismatch is to adjust the canonical labeling of
full and almost complete trees.
• Start the node labeling from 0 (rather than 1).
• The children of node k are now nodes (2k+1) and (2k+2), and the parent of
node k is (k-1)/2, integer division.
21
Application of Almost Complete Binary Trees:
Heaps
• A heap (or min-heap to be precise) is an almost complete binary tree
where
• Every node holds a data value (or key)
• The key of every node is ≤ the keys of the children
Note:
A max-heap has the same definition except that the
Key of every node is >= the keys of the children
22
Example of a Min-heap
16
5
8
15 11
18 12
20
27
33
30
23
Operations on Heaps
• Delete the minimum value and return it. This
operation is called deleteMin.
• Insert a new data value
Applications of Heaps:
• A heap implements a priority queue, which is a queue
that orders entities not a on first-come first-serve basis,
but on a priority basis: the item of highest priority is at
the head, and the item of the lowest priority is at the tail
• Another application: sorting, which will be seen later
24
DeleteMin in Min-heaps
• The minimum value in a min-heap is at the root!
• To delete the min, you can’t just remove the data value of the root,
because every node must hold a key
• Instead, take the last node from the heap, move its key to the root,
and delete that last node
• But now, the tree is no longer a heap (still almost complete, but the
root key value may no longer be ≤ the keys of its children
25
Illustration of First Stage of deletemin
16
5
8
15 11
18 12
20
27
33
30
16
8
15 11
18 12
20
27
33
30
16
8
15 11
18
12
20
27
33
30
16
8
15 11
18
12
20
27
33
30
26
Restore Heap
• To bring the structure back to its “heapness”, we
restore the heap
• Swap the new root key with the smaller child.
• Now the potential bug is at the one level down. If
it is not already ≤ the keys of its children, swap it
with its smaller child
• Keep repeating the last step until the “bug” key
becomes ≤ its children, or the it becomes a leaf
27
Illustration of Restore-Heap
16
8
15 11
18
12
20
27
33
30
16
12
15 11
18
8
20
27
33
30
16
11
15 12
18
8
20
27
33
30
Now it is a correct heap
28
Time complexity of insert and deletmin
• Both operations takes time proportional to the
height of the tree
• When restoring the heap, the bug moves from level to
level until, in the worst case, it becomes a leaf (in
deletemin) or the root (in insert)
• Each move to a new level takes constant time
• Therefore, the time is proportional to the number of
levels, which is the height of the tree.
• But the height is O(log n)
• Therefore, both insert and deletemin take O(log n)
time, which is very fast.
29
Inserting into a minheap
• Suppose you want to insert a new value x into the heap
• Create a new node at the “end” of the heap (or put x at the end of
the array)
• If x is >= its parent, done
• Otherwise, we have to restore the heap:
• Repeatedly swap x with its parent until either x reaches the root of x becomes
>= its parent
30
Illustration of Insertion Into the Heap
• In class
31
The Min-heap Class in C++
class Minheap{ //the heap is implemented with a dynamic array
public:
typedef int datatype;
Minheap(int cap = 10){capacity=cap; length=0;
ptr = new datatype[cap];};
datatype deleteMin( );
void insert(datatype x);
bool isEmpty( ) {return length==0;};
int size( ) {return length;};
private:
datatype *ptr; // points to the array
int capacity;
int length;
void doubleCapacity(); //doubles the capacity when needed
};
32
Code for deletemin
Minheap::datatype Minheap::deleteMin( ){
assert(length>0);
datatype returnValue = ptr[0];
length--; ptr[0]=ptr[length]; // move last value to root element
int i=0;
while ((2*i+1<length && ptr[i]>ptr[2*i+1]) ||
(2*i+2<length && (ptr[i]>ptr[2*i+1] ||
ptr[i]>ptr[2*i+2]))){ // “bug” still > at least one child
if (ptr[2*i+1] <= ptr[2*i+2]){ // left child is the smaller child
datatype tmp= ptr[i]; ptr[i]=ptr[2*i+1]; ptr[2*i+1]=tmp; //swap
i=2*i+1; }
else{ // right child if the smaller child. Swap bug with right child.
datatype tmp= ptr[i]; ptr[i]=ptr[2*i+2]; ptr[2*i+2]=tmp; // swap
i=2*i+2; }
}
return returnValue;
};
33
Code for Insert
void Minheap::insert(datatype x){
if (length==capacity)
doubleCapacity();
ptr[length]=x;
int i=length;
length++;
while (i>0 && ptr[i] < ptr[i/2]){
datatype tmp= ptr[i];
ptr[i]=ptr[(i-1)/2];
ptr[(i-1)/2]=tmp;
i=(i-1)/2;
}
};
34
Code for doubleCapacity
void Minheap::doubleCapacity(){
capacity = 2*capacity;
datatype *newptr = new datatype[capacity];
for (int i=0;i<length;i++)
newptr[i]=ptr[i];
delete [] ptr;
ptr = newptr;
};

Mais conteúdo relacionado

Mais procurados

B trees in Data Structure
B trees in Data StructureB trees in Data Structure
B trees in Data Structure
Anuj Modi
 

Mais procurados (20)

Tree and Binary Search tree
Tree and Binary Search treeTree and Binary Search tree
Tree and Binary Search tree
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
trees in data structure
trees in data structure trees in data structure
trees in data structure
 
Graph in data structure
Graph in data structureGraph in data structure
Graph in data structure
 
Red black tree
Red black treeRed black tree
Red black tree
 
Data Structure (Tree)
Data Structure (Tree)Data Structure (Tree)
Data Structure (Tree)
 
Trees
TreesTrees
Trees
 
Terminology of tree
Terminology of treeTerminology of tree
Terminology of tree
 
Binary search tree in data structures
Binary search tree in  data structuresBinary search tree in  data structures
Binary search tree in data structures
 
linked list in Data Structure, Simple and Easy Tutorial
linked list in Data Structure, Simple and Easy Tutoriallinked list in Data Structure, Simple and Easy Tutorial
linked list in Data Structure, Simple and Easy Tutorial
 
Trees data structure
Trees data structureTrees data structure
Trees data structure
 
B trees in Data Structure
B trees in Data StructureB trees in Data Structure
B trees in Data Structure
 
Binary tree
Binary  treeBinary  tree
Binary tree
 
Binary trees1
Binary trees1Binary trees1
Binary trees1
 
single linked list
single linked listsingle linked list
single linked list
 
Linear data structure concepts
Linear data structure conceptsLinear data structure concepts
Linear data structure concepts
 
Data Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search TreeData Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search Tree
 
AVL Tree
AVL TreeAVL Tree
AVL Tree
 
Binary Tree Traversal
Binary Tree TraversalBinary Tree Traversal
Binary Tree Traversal
 
Threaded Binary Tree
Threaded Binary TreeThreaded Binary Tree
Threaded Binary Tree
 

Semelhante a Tree traversal techniques

lecture10 date structure types of graph and terminology
lecture10 date structure types of graph and terminologylecture10 date structure types of graph and terminology
lecture10 date structure types of graph and terminology
KamranAli649587
 
tree-160731205832.pptx
tree-160731205832.pptxtree-160731205832.pptx
tree-160731205832.pptx
MouDhara1
 
5220191CS146 Data Structures and AlgorithmsC.docx
5220191CS146 Data Structures and AlgorithmsC.docx5220191CS146 Data Structures and AlgorithmsC.docx
5220191CS146 Data Structures and AlgorithmsC.docx
fredharris32
 

Semelhante a Tree traversal techniques (20)

lecture10 date structure types of graph and terminology
lecture10 date structure types of graph and terminologylecture10 date structure types of graph and terminology
lecture10 date structure types of graph and terminology
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
Heapsort
HeapsortHeapsort
Heapsort
 
Heapsort
HeapsortHeapsort
Heapsort
 
tree-160731205832.pptx
tree-160731205832.pptxtree-160731205832.pptx
tree-160731205832.pptx
 
Trees
TreesTrees
Trees
 
part4-trees.ppt
part4-trees.pptpart4-trees.ppt
part4-trees.ppt
 
BINARY TREE REPRESENTATION.ppt
BINARY TREE REPRESENTATION.pptBINARY TREE REPRESENTATION.ppt
BINARY TREE REPRESENTATION.ppt
 
210 trees
210 trees210 trees
210 trees
 
210 trees5
210 trees5210 trees5
210 trees5
 
Binary tree
Binary treeBinary tree
Binary tree
 
Binary tree
Binary treeBinary tree
Binary tree
 
BINARY SEARCH TREE
BINARY SEARCH TREEBINARY SEARCH TREE
BINARY SEARCH TREE
 
Binary tree
Binary tree Binary tree
Binary tree
 
Tree
TreeTree
Tree
 
heaps2
heaps2heaps2
heaps2
 
data_structures_and_applications_-_module-4.ppt
data_structures_and_applications_-_module-4.pptdata_structures_and_applications_-_module-4.ppt
data_structures_and_applications_-_module-4.ppt
 
L 17 ct1120
L 17 ct1120L 17 ct1120
L 17 ct1120
 
binary tree
binary treebinary tree
binary tree
 
5220191CS146 Data Structures and AlgorithmsC.docx
5220191CS146 Data Structures and AlgorithmsC.docx5220191CS146 Data Structures and AlgorithmsC.docx
5220191CS146 Data Structures and AlgorithmsC.docx
 

Mais de Syed Zaid Irshad

Basic Concept of Information Technology
Basic Concept of Information TechnologyBasic Concept of Information Technology
Basic Concept of Information Technology
Syed Zaid Irshad
 
Introduction to ICS 1st Year Book
Introduction to ICS 1st Year BookIntroduction to ICS 1st Year Book
Introduction to ICS 1st Year Book
Syed Zaid Irshad
 

Mais de Syed Zaid Irshad (20)

Operating System.pdf
Operating System.pdfOperating System.pdf
Operating System.pdf
 
DBMS_Lab_Manual_&_Solution
DBMS_Lab_Manual_&_SolutionDBMS_Lab_Manual_&_Solution
DBMS_Lab_Manual_&_Solution
 
Data Structure and Algorithms.pptx
Data Structure and Algorithms.pptxData Structure and Algorithms.pptx
Data Structure and Algorithms.pptx
 
Design and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptxDesign and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptx
 
Professional Issues in Computing
Professional Issues in ComputingProfessional Issues in Computing
Professional Issues in Computing
 
Reduce course notes class xi
Reduce course notes class xiReduce course notes class xi
Reduce course notes class xi
 
Reduce course notes class xii
Reduce course notes class xiiReduce course notes class xii
Reduce course notes class xii
 
Introduction to Database
Introduction to DatabaseIntroduction to Database
Introduction to Database
 
C Language
C LanguageC Language
C Language
 
Flowchart
FlowchartFlowchart
Flowchart
 
Algorithm Pseudo
Algorithm PseudoAlgorithm Pseudo
Algorithm Pseudo
 
Computer Programming
Computer ProgrammingComputer Programming
Computer Programming
 
ICS 2nd Year Book Introduction
ICS 2nd Year Book IntroductionICS 2nd Year Book Introduction
ICS 2nd Year Book Introduction
 
Security, Copyright and the Law
Security, Copyright and the LawSecurity, Copyright and the Law
Security, Copyright and the Law
 
Computer Architecture
Computer ArchitectureComputer Architecture
Computer Architecture
 
Data Communication
Data CommunicationData Communication
Data Communication
 
Information Networks
Information NetworksInformation Networks
Information Networks
 
Basic Concept of Information Technology
Basic Concept of Information TechnologyBasic Concept of Information Technology
Basic Concept of Information Technology
 
Introduction to ICS 1st Year Book
Introduction to ICS 1st Year BookIntroduction to ICS 1st Year Book
Introduction to ICS 1st Year Book
 
Using the set operators
Using the set operatorsUsing the set operators
Using the set operators
 

Último

Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Christo Ananth
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
Tonystark477637
 
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
 

Último (20)

VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
 
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLPVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01
 
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...
 
UNIT-IFLUID PROPERTIES & FLOW CHARACTERISTICS
UNIT-IFLUID PROPERTIES & FLOW CHARACTERISTICSUNIT-IFLUID PROPERTIES & FLOW CHARACTERISTICS
UNIT-IFLUID PROPERTIES & FLOW CHARACTERISTICS
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
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...
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 

Tree traversal techniques

  • 1. 1 Tree Traversal Techniques; Heaps •Tree Traversal Concept •Tree Traversal Techniques: Preorder, Inorder, Postorder •Full Trees •Almost Complete Trees •Heaps
  • 2. 2 Binary-Tree Related Definitions • The children of any node in a binary tree are ordered into a left child and a right child • A node can have a left and a right child, a left child only, a right child only, or no children • The tree made up of a left child (of a node x) and all its descendents is called the left subtree of x • Right subtrees are defined similarly 10 1 3 11 98 4 6 5 7 12
  • 3. 3 A Binary-tree Node Class class TreeNode { public: typedef int datatype; TreeNode(datatype x=0, TreeNode *left=NULL, TreeNode *right=NULL){ data=x; this->left=left; this->right=right; }; datatype getData( ) {return data;}; TreeNode *getLeft( ) {return left;}; TreeNode *getRight( ) {return right;}; void setData(datatype x) {data=x;}; void setLeft(TreeNode *ptr) {left=ptr;}; void setRight(TreeNode *ptr) {right=ptr;}; private: datatype data; // different data type for other apps TreeNode *left; // the pointer to left child TreeNode *right; // the pointer to right child };
  • 4. 4 Binary Tree Class class Tree { public: typedef int datatype; Tree(TreeNode *rootPtr=NULL){this->rootPtr=rootPtr;}; TreeNode *search(datatype x); bool insert(datatype x); TreeNode * remove(datatype x); TreeNode *getRoot(){return rootPtr;}; Tree *getLeftSubtree(); Tree *getRightSubtree(); bool isEmpty(){return rootPtr == NULL;}; private: TreeNode *rootPtr; };
  • 5. 5 Binary Tree Traversal • Traversal is the process of visiting every node once • Visiting a node entails doing some processing at that node, but when describing a traversal strategy, we need not concern ourselves with what that processing is
  • 6. 6 Binary Tree Traversal Techniques • Three recursive techniques for binary tree traversal • In each technique, the left subtree is traversed recursively, the right subtree is traversed recursively, and the root is visited • What distinguishes the techniques from one another is the order of those 3 tasks
  • 7. 7 Preoder, Inorder, Postorder • In Preorder, the root is visited before (pre) the subtrees traversals • In Inorder, the root is visited in-between left and right subtree traversal • In Preorder, the root is visited after (pre) the subtrees traversals Preorder Traversal: 1. Visit the root 2. Traverse left subtree 3. Traverse right subtree Inorder Traversal: 1. Traverse left subtree 2. Visit the root 3. Traverse right subtree Postorder Traversal: 1. Traverse left subtree 2. Traverse right subtree 3. Visit the root
  • 8. 8 Illustrations for Traversals • Assume: visiting a node is printing its label • Preorder: 1 3 5 4 6 7 8 9 10 11 12 • Inorder: 4 5 6 3 1 8 7 9 11 10 12 • Postorder: 4 6 5 3 8 11 12 10 9 7 1 1 3 11 98 4 6 5 7 12 10
  • 9. 9 Illustrations for Traversals (Contd.) • Assume: visiting a node is printing its data • Preorder: 15 8 2 6 3 7 11 10 12 14 20 27 22 30 • Inorder: 2 3 6 7 8 10 11 12 14 15 20 22 27 30 • Postorder: 3 7 6 2 10 14 12 11 8 22 30 27 20 15 6 15 8 2 3 7 11 10 14 12 20 27 22 30
  • 10. 10 Code for the Traversal Techniques • The code for visit is up to you to provide, depending on the application • A typical example for visit(…) is to print out the data part of its input node void inOrder(Tree *tree){ if (tree->isEmpty( )) return; inOrder(tree->getLeftSubtree( )); visit(tree->getRoot( )); inOrder(tree->getRightSubtree( )); } void preOrder(Tree *tree){ if (tree->isEmpty( )) return; visit(tree->getRoot( )); preOrder(tree->getLeftSubtree()); preOrder(tree->getRightSubtree()); } void postOrder(Tree *tree){ if (tree->isEmpty( )) return; postOrder(tree->getLeftSubtree( )); postOrder(tree->getRightSubtree( )); visit(tree->getRoot( )); }
  • 11. 11 Application of Traversal Sorting a BST • Observe the output of the inorder traversal of the BST example two slides earlier • It is sorted • This is no coincidence • As a general rule, if you output the keys (data) of the nodes of a BST using inorder traversal, the data comes out sorted in increasing order
  • 12. 12 Other Kinds of Binary Trees (Full Binary Trees) • Full Binary Tree: A full binary tree is a binary tree where all the leaves are on the same level and every non-leaf has two children • The first four full binary trees are:
  • 13. 13 Examples of Non-Full Binary Trees • These trees are NOT full binary trees: (do you know why?)
  • 14. 14 Canonical Labeling of Full Binary Trees • Label the nodes from 1 to n from the top to the bottom, left to right 1 1 2 3 1 2 3 4 5 6 7 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Relationships between labels of children and parent: 2i 2i+1 i
  • 15. 15 Other Kinds of Binary Trees (Almost Complete Binary trees) • Almost Complete Binary Tree: An almost complete binary tree of n nodes, for any arbitrary nonnegative integer n, is the binary tree made up of the first n nodes of a canonically labeled full binary 1 1 2 1 2 3 4 5 6 7 1 2 1 2 3 4 5 6 1 2 3 4 1 2 3 4 5
  • 16. 16 Depth/Height of Full Trees and Almost Complete Trees • The height (or depth ) h of such trees is O(log n) • Proof: In the case of full trees, • The number of nodes n is: n=1+2+22+23+…+2h=2h+1-1 • Therefore, 2h+1 = n+1, and thus, h=log(n+1)-1 • Hence, h=O(log n) • For almost complete trees, the proof is left as an exercise.
  • 17. 17 Canonical Labeling of Almost Complete Binary Trees • Same labeling inherited from full binary trees • Same relationship holding between the labels of children and parents: Relationships between labels of children and parent: 2i 2i+1 i
  • 18. 18 Array Representation of Full Trees and Almost Complete Trees • A canonically label-able tree, like full binary trees and almost complete binary trees, can be represented by an array A of the same length as the number of nodes • A[k] is identified with node of label k • That is, A[k] holds the data of node k • Advantage: • no need to store left and right pointers in the nodes  save memory • Direct access to nodes: to get to node k, access A[k]
  • 19. 19 Illustration of Array Representation • Notice: Left child of A[5] (of data 11) is A[2*5]=A[10] (of data 18), and its right child is A[2*5+1]=A[11] (of data 12). • Parent of A[4] is A[4/2]=A[2], and parent of A[5]=A[5/2]=A[2] 6 15 8 2 11 18 12 20 27 13 30 15 8 20 2 11 30 27 13 6 10 12 1 2 3 4 5 6 7 8 9 10 11
  • 20. 20 Adjustment of Indexes • Notice that in the previous slides, the node labels start from 1, and so would the corresponding arrays • But in C/C++, array indices start from 0 • The best way to handle the mismatch is to adjust the canonical labeling of full and almost complete trees. • Start the node labeling from 0 (rather than 1). • The children of node k are now nodes (2k+1) and (2k+2), and the parent of node k is (k-1)/2, integer division.
  • 21. 21 Application of Almost Complete Binary Trees: Heaps • A heap (or min-heap to be precise) is an almost complete binary tree where • Every node holds a data value (or key) • The key of every node is ≤ the keys of the children Note: A max-heap has the same definition except that the Key of every node is >= the keys of the children
  • 22. 22 Example of a Min-heap 16 5 8 15 11 18 12 20 27 33 30
  • 23. 23 Operations on Heaps • Delete the minimum value and return it. This operation is called deleteMin. • Insert a new data value Applications of Heaps: • A heap implements a priority queue, which is a queue that orders entities not a on first-come first-serve basis, but on a priority basis: the item of highest priority is at the head, and the item of the lowest priority is at the tail • Another application: sorting, which will be seen later
  • 24. 24 DeleteMin in Min-heaps • The minimum value in a min-heap is at the root! • To delete the min, you can’t just remove the data value of the root, because every node must hold a key • Instead, take the last node from the heap, move its key to the root, and delete that last node • But now, the tree is no longer a heap (still almost complete, but the root key value may no longer be ≤ the keys of its children
  • 25. 25 Illustration of First Stage of deletemin 16 5 8 15 11 18 12 20 27 33 30 16 8 15 11 18 12 20 27 33 30 16 8 15 11 18 12 20 27 33 30 16 8 15 11 18 12 20 27 33 30
  • 26. 26 Restore Heap • To bring the structure back to its “heapness”, we restore the heap • Swap the new root key with the smaller child. • Now the potential bug is at the one level down. If it is not already ≤ the keys of its children, swap it with its smaller child • Keep repeating the last step until the “bug” key becomes ≤ its children, or the it becomes a leaf
  • 27. 27 Illustration of Restore-Heap 16 8 15 11 18 12 20 27 33 30 16 12 15 11 18 8 20 27 33 30 16 11 15 12 18 8 20 27 33 30 Now it is a correct heap
  • 28. 28 Time complexity of insert and deletmin • Both operations takes time proportional to the height of the tree • When restoring the heap, the bug moves from level to level until, in the worst case, it becomes a leaf (in deletemin) or the root (in insert) • Each move to a new level takes constant time • Therefore, the time is proportional to the number of levels, which is the height of the tree. • But the height is O(log n) • Therefore, both insert and deletemin take O(log n) time, which is very fast.
  • 29. 29 Inserting into a minheap • Suppose you want to insert a new value x into the heap • Create a new node at the “end” of the heap (or put x at the end of the array) • If x is >= its parent, done • Otherwise, we have to restore the heap: • Repeatedly swap x with its parent until either x reaches the root of x becomes >= its parent
  • 30. 30 Illustration of Insertion Into the Heap • In class
  • 31. 31 The Min-heap Class in C++ class Minheap{ //the heap is implemented with a dynamic array public: typedef int datatype; Minheap(int cap = 10){capacity=cap; length=0; ptr = new datatype[cap];}; datatype deleteMin( ); void insert(datatype x); bool isEmpty( ) {return length==0;}; int size( ) {return length;}; private: datatype *ptr; // points to the array int capacity; int length; void doubleCapacity(); //doubles the capacity when needed };
  • 32. 32 Code for deletemin Minheap::datatype Minheap::deleteMin( ){ assert(length>0); datatype returnValue = ptr[0]; length--; ptr[0]=ptr[length]; // move last value to root element int i=0; while ((2*i+1<length && ptr[i]>ptr[2*i+1]) || (2*i+2<length && (ptr[i]>ptr[2*i+1] || ptr[i]>ptr[2*i+2]))){ // “bug” still > at least one child if (ptr[2*i+1] <= ptr[2*i+2]){ // left child is the smaller child datatype tmp= ptr[i]; ptr[i]=ptr[2*i+1]; ptr[2*i+1]=tmp; //swap i=2*i+1; } else{ // right child if the smaller child. Swap bug with right child. datatype tmp= ptr[i]; ptr[i]=ptr[2*i+2]; ptr[2*i+2]=tmp; // swap i=2*i+2; } } return returnValue; };
  • 33. 33 Code for Insert void Minheap::insert(datatype x){ if (length==capacity) doubleCapacity(); ptr[length]=x; int i=length; length++; while (i>0 && ptr[i] < ptr[i/2]){ datatype tmp= ptr[i]; ptr[i]=ptr[(i-1)/2]; ptr[(i-1)/2]=tmp; i=(i-1)/2; } };
  • 34. 34 Code for doubleCapacity void Minheap::doubleCapacity(){ capacity = 2*capacity; datatype *newptr = new datatype[capacity]; for (int i=0;i<length;i++) newptr[i]=ptr[i]; delete [] ptr; ptr = newptr; };