SlideShare a Scribd company logo
1 of 34
CS 103 1
Tree Traversal Techniques;
Heaps
• Tree Traversal Concept
• Tree Traversal Techniques: Preorder,
Inorder, Postorder
• Full Trees
• Almost Complete Trees
• Heaps
CS 103 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
9
8
4 6
5
7
12
CS 103 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
};
CS 103 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;
};
CS 103 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
CS 103 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
CS 103 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
CS 103 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
9
8
4 6
5
7
12
10
CS 103 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
CS 103 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( ));
}
CS 103 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
CS 103 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:
CS 103 13
Examples of Non-Full Binary Trees
• These trees are NOT full binary trees: (do
you know why?)
CS 103 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
1213 14 15
Relationships between labels
of children and parent:
2i 2i+1
i
CS 103 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
CS 103 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.
CS 103 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
CS 103 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]
CS 103 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
CS 103 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.
CS 103 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
CS 103 22
Example of a Min-heap
16
5
8
15 11
18 12
20
27
33
30
CS 103 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
CS 103 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
CS 103 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
CS 103 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
CS 103 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
CS 103 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.
CS 103 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
CS 103 30
Illustration of Insertion Into the Heap
• In class
CS 103 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
};
CS 103 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;
};
CS 103 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;
}
};
CS 103 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;
};

More Related Content

Similar to lecture10 date structure types of graph and terminology

Similar to lecture10 date structure types of graph and terminology (20)

Binary tree
Binary treeBinary tree
Binary tree
 
BINARY SEARCH TREE
BINARY SEARCH TREEBINARY SEARCH TREE
BINARY SEARCH TREE
 
210 trees
210 trees210 trees
210 trees
 
210 trees5
210 trees5210 trees5
210 trees5
 
Tree
TreeTree
Tree
 
Tree
TreeTree
Tree
 
s11_bin_search_trees.ppt
s11_bin_search_trees.ppts11_bin_search_trees.ppt
s11_bin_search_trees.ppt
 
b-tree.ppt
b-tree.pptb-tree.ppt
b-tree.ppt
 
Data Structure: TREES
Data Structure: TREESData Structure: TREES
Data Structure: TREES
 
7.tree
7.tree7.tree
7.tree
 
trees-and-graphs_computer_science_for_student.pptx
trees-and-graphs_computer_science_for_student.pptxtrees-and-graphs_computer_science_for_student.pptx
trees-and-graphs_computer_science_for_student.pptx
 
BTrees-fall2010.ppt
BTrees-fall2010.pptBTrees-fall2010.ppt
BTrees-fall2010.ppt
 
Trees in data structure
Trees in data structureTrees in data structure
Trees in data structure
 
unit06-3-Trees.pdf
unit06-3-Trees.pdfunit06-3-Trees.pdf
unit06-3-Trees.pdf
 
binary tree
binary treebinary tree
binary tree
 
Module - 5_Trees.pdf
Module - 5_Trees.pdfModule - 5_Trees.pdf
Module - 5_Trees.pdf
 
Lecture notes data structures tree
Lecture notes data structures   treeLecture notes data structures   tree
Lecture notes data structures tree
 
Tree.pptx
Tree.pptxTree.pptx
Tree.pptx
 
Editors l21 l24
Editors l21 l24Editors l21 l24
Editors l21 l24
 
5220191CS146 Data Structures and AlgorithmsC.docx
5220191CS146 Data Structures and AlgorithmsC.docx5220191CS146 Data Structures and AlgorithmsC.docx
5220191CS146 Data Structures and AlgorithmsC.docx
 

More from KamranAli649587

More from KamranAli649587 (20)

UNIT-2-liang-barsky-clipping-algorithm-KM.pdf
UNIT-2-liang-barsky-clipping-algorithm-KM.pdfUNIT-2-liang-barsky-clipping-algorithm-KM.pdf
UNIT-2-liang-barsky-clipping-algorithm-KM.pdf
 
Data design and analysis of computing tools
Data design and analysis of computing toolsData design and analysis of computing tools
Data design and analysis of computing tools
 
graphs data structure and algorithm link list
graphs data structure and algorithm link listgraphs data structure and algorithm link list
graphs data structure and algorithm link list
 
Encoder-and-decoder.pptx
Encoder-and-decoder.pptxEncoder-and-decoder.pptx
Encoder-and-decoder.pptx
 
Radio propagation model...pptx
Radio propagation model...pptxRadio propagation model...pptx
Radio propagation model...pptx
 
Loops_and_FunctionsWeek4_0.ppt
Loops_and_FunctionsWeek4_0.pptLoops_and_FunctionsWeek4_0.ppt
Loops_and_FunctionsWeek4_0.ppt
 
Lecture+06-TypesVars.ppt
Lecture+06-TypesVars.pptLecture+06-TypesVars.ppt
Lecture+06-TypesVars.ppt
 
C++InputOutput.PPT
C++InputOutput.PPTC++InputOutput.PPT
C++InputOutput.PPT
 
radiopropagation-140328202308-phpapp01.pdf
radiopropagation-140328202308-phpapp01.pdfradiopropagation-140328202308-phpapp01.pdf
radiopropagation-140328202308-phpapp01.pdf
 
cluster.pptx
cluster.pptxcluster.pptx
cluster.pptx
 
Week11-EvaluationMethods.ppt
Week11-EvaluationMethods.pptWeek11-EvaluationMethods.ppt
Week11-EvaluationMethods.ppt
 
Week6-Sectionsofapaper.ppt
Week6-Sectionsofapaper.pptWeek6-Sectionsofapaper.ppt
Week6-Sectionsofapaper.ppt
 
null-13.pdf
null-13.pdfnull-13.pdf
null-13.pdf
 
Reaches
ReachesReaches
Reaches
 
null-6.pdf
null-6.pdfnull-6.pdf
null-6.pdf
 
null-1.pptx
null-1.pptxnull-1.pptx
null-1.pptx
 
Lect-01.ppt
Lect-01.pptLect-01.ppt
Lect-01.ppt
 
Db_05.ppt
Db_05.pptDb_05.ppt
Db_05.ppt
 
ch7.ppt
ch7.pptch7.ppt
ch7.ppt
 
lect09.ppt
lect09.pptlect09.ppt
lect09.ppt
 

Recently uploaded

Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...Jack DiGiovanna
 
From idea to production in a day – Leveraging Azure ML and Streamlit to build...
From idea to production in a day – Leveraging Azure ML and Streamlit to build...From idea to production in a day – Leveraging Azure ML and Streamlit to build...
From idea to production in a day – Leveraging Azure ML and Streamlit to build...Florian Roscheck
 
04242024_CCC TUG_Joins and Relationships
04242024_CCC TUG_Joins and Relationships04242024_CCC TUG_Joins and Relationships
04242024_CCC TUG_Joins and Relationshipsccctableauusergroup
 
How we prevented account sharing with MFA
How we prevented account sharing with MFAHow we prevented account sharing with MFA
How we prevented account sharing with MFAAndrei Kaleshka
 
Customer Service Analytics - Make Sense of All Your Data.pptx
Customer Service Analytics - Make Sense of All Your Data.pptxCustomer Service Analytics - Make Sense of All Your Data.pptx
Customer Service Analytics - Make Sense of All Your Data.pptxEmmanuel Dauda
 
Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)
Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)
Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)jennyeacort
 
Beautiful Sapna Vip Call Girls Hauz Khas 9711199012 Call /Whatsapps
Beautiful Sapna Vip  Call Girls Hauz Khas 9711199012 Call /WhatsappsBeautiful Sapna Vip  Call Girls Hauz Khas 9711199012 Call /Whatsapps
Beautiful Sapna Vip Call Girls Hauz Khas 9711199012 Call /Whatsappssapnasaifi408
 
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.pptdokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.pptSonatrach
 
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdfKantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdfSocial Samosa
 
NLP Project PPT: Flipkart Product Reviews through NLP Data Science.pptx
NLP Project PPT: Flipkart Product Reviews through NLP Data Science.pptxNLP Project PPT: Flipkart Product Reviews through NLP Data Science.pptx
NLP Project PPT: Flipkart Product Reviews through NLP Data Science.pptxBoston Institute of Analytics
 
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样vhwb25kk
 
INTERNSHIP ON PURBASHA COMPOSITE TEX LTD
INTERNSHIP ON PURBASHA COMPOSITE TEX LTDINTERNSHIP ON PURBASHA COMPOSITE TEX LTD
INTERNSHIP ON PURBASHA COMPOSITE TEX LTDRafezzaman
 
B2 Creative Industry Response Evaluation.docx
B2 Creative Industry Response Evaluation.docxB2 Creative Industry Response Evaluation.docx
B2 Creative Industry Response Evaluation.docxStephen266013
 
RABBIT: A CLI tool for identifying bots based on their GitHub events.
RABBIT: A CLI tool for identifying bots based on their GitHub events.RABBIT: A CLI tool for identifying bots based on their GitHub events.
RABBIT: A CLI tool for identifying bots based on their GitHub events.natarajan8993
 
Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...
Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...
Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...dajasot375
 
办理(UWIC毕业证书)英国卡迪夫城市大学毕业证成绩单原版一比一
办理(UWIC毕业证书)英国卡迪夫城市大学毕业证成绩单原版一比一办理(UWIC毕业证书)英国卡迪夫城市大学毕业证成绩单原版一比一
办理(UWIC毕业证书)英国卡迪夫城市大学毕业证成绩单原版一比一F La
 
原版1:1定制南十字星大学毕业证(SCU毕业证)#文凭成绩单#真实留信学历认证永久存档
原版1:1定制南十字星大学毕业证(SCU毕业证)#文凭成绩单#真实留信学历认证永久存档原版1:1定制南十字星大学毕业证(SCU毕业证)#文凭成绩单#真实留信学历认证永久存档
原版1:1定制南十字星大学毕业证(SCU毕业证)#文凭成绩单#真实留信学历认证永久存档208367051
 
科罗拉多大学波尔得分校毕业证学位证成绩单-可办理
科罗拉多大学波尔得分校毕业证学位证成绩单-可办理科罗拉多大学波尔得分校毕业证学位证成绩单-可办理
科罗拉多大学波尔得分校毕业证学位证成绩单-可办理e4aez8ss
 
PKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptxPKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptxPramod Kumar Srivastava
 

Recently uploaded (20)

Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
 
From idea to production in a day – Leveraging Azure ML and Streamlit to build...
From idea to production in a day – Leveraging Azure ML and Streamlit to build...From idea to production in a day – Leveraging Azure ML and Streamlit to build...
From idea to production in a day – Leveraging Azure ML and Streamlit to build...
 
04242024_CCC TUG_Joins and Relationships
04242024_CCC TUG_Joins and Relationships04242024_CCC TUG_Joins and Relationships
04242024_CCC TUG_Joins and Relationships
 
How we prevented account sharing with MFA
How we prevented account sharing with MFAHow we prevented account sharing with MFA
How we prevented account sharing with MFA
 
Customer Service Analytics - Make Sense of All Your Data.pptx
Customer Service Analytics - Make Sense of All Your Data.pptxCustomer Service Analytics - Make Sense of All Your Data.pptx
Customer Service Analytics - Make Sense of All Your Data.pptx
 
Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)
Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)
Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)
 
Beautiful Sapna Vip Call Girls Hauz Khas 9711199012 Call /Whatsapps
Beautiful Sapna Vip  Call Girls Hauz Khas 9711199012 Call /WhatsappsBeautiful Sapna Vip  Call Girls Hauz Khas 9711199012 Call /Whatsapps
Beautiful Sapna Vip Call Girls Hauz Khas 9711199012 Call /Whatsapps
 
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.pptdokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
dokumen.tips_chapter-4-transient-heat-conduction-mehmet-kanoglu.ppt
 
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdfKantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
Kantar AI Summit- Under Embargo till Wednesday, 24th April 2024, 4 PM, IST.pdf
 
NLP Project PPT: Flipkart Product Reviews through NLP Data Science.pptx
NLP Project PPT: Flipkart Product Reviews through NLP Data Science.pptxNLP Project PPT: Flipkart Product Reviews through NLP Data Science.pptx
NLP Project PPT: Flipkart Product Reviews through NLP Data Science.pptx
 
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
1:1定制(UQ毕业证)昆士兰大学毕业证成绩单修改留信学历认证原版一模一样
 
INTERNSHIP ON PURBASHA COMPOSITE TEX LTD
INTERNSHIP ON PURBASHA COMPOSITE TEX LTDINTERNSHIP ON PURBASHA COMPOSITE TEX LTD
INTERNSHIP ON PURBASHA COMPOSITE TEX LTD
 
B2 Creative Industry Response Evaluation.docx
B2 Creative Industry Response Evaluation.docxB2 Creative Industry Response Evaluation.docx
B2 Creative Industry Response Evaluation.docx
 
E-Commerce Order PredictionShraddha Kamble.pptx
E-Commerce Order PredictionShraddha Kamble.pptxE-Commerce Order PredictionShraddha Kamble.pptx
E-Commerce Order PredictionShraddha Kamble.pptx
 
RABBIT: A CLI tool for identifying bots based on their GitHub events.
RABBIT: A CLI tool for identifying bots based on their GitHub events.RABBIT: A CLI tool for identifying bots based on their GitHub events.
RABBIT: A CLI tool for identifying bots based on their GitHub events.
 
Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...
Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...
Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...
 
办理(UWIC毕业证书)英国卡迪夫城市大学毕业证成绩单原版一比一
办理(UWIC毕业证书)英国卡迪夫城市大学毕业证成绩单原版一比一办理(UWIC毕业证书)英国卡迪夫城市大学毕业证成绩单原版一比一
办理(UWIC毕业证书)英国卡迪夫城市大学毕业证成绩单原版一比一
 
原版1:1定制南十字星大学毕业证(SCU毕业证)#文凭成绩单#真实留信学历认证永久存档
原版1:1定制南十字星大学毕业证(SCU毕业证)#文凭成绩单#真实留信学历认证永久存档原版1:1定制南十字星大学毕业证(SCU毕业证)#文凭成绩单#真实留信学历认证永久存档
原版1:1定制南十字星大学毕业证(SCU毕业证)#文凭成绩单#真实留信学历认证永久存档
 
科罗拉多大学波尔得分校毕业证学位证成绩单-可办理
科罗拉多大学波尔得分校毕业证学位证成绩单-可办理科罗拉多大学波尔得分校毕业证学位证成绩单-可办理
科罗拉多大学波尔得分校毕业证学位证成绩单-可办理
 
PKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptxPKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptx
 

lecture10 date structure types of graph and terminology

  • 1. CS 103 1 Tree Traversal Techniques; Heaps • Tree Traversal Concept • Tree Traversal Techniques: Preorder, Inorder, Postorder • Full Trees • Almost Complete Trees • Heaps
  • 2. CS 103 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 9 8 4 6 5 7 12
  • 3. CS 103 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. CS 103 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. CS 103 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. CS 103 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. CS 103 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. CS 103 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 9 8 4 6 5 7 12 10
  • 9. CS 103 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. CS 103 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. CS 103 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. CS 103 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. CS 103 13 Examples of Non-Full Binary Trees • These trees are NOT full binary trees: (do you know why?)
  • 14. CS 103 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 1213 14 15 Relationships between labels of children and parent: 2i 2i+1 i
  • 15. CS 103 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. CS 103 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. CS 103 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. CS 103 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. CS 103 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. CS 103 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. CS 103 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. CS 103 22 Example of a Min-heap 16 5 8 15 11 18 12 20 27 33 30
  • 23. CS 103 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. CS 103 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. CS 103 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. CS 103 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. CS 103 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. CS 103 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. CS 103 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. CS 103 30 Illustration of Insertion Into the Heap • In class
  • 31. CS 103 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. CS 103 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. CS 103 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. CS 103 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; };