SlideShare a Scribd company logo
Write a function in C++ to generate an N-node random binary search tree with distinct keys 1
through N.
Assume that you have available a function, randInt(lower,upper), that generates a uniform
random integer in the appropriate closed interval.
What is the running time of your routine?
Solution
/ A C++ prgroam to contrcut all unique BSTs for keys from 1 to n
#include
#include
using namespace std;
// node structure
struct node
{
int key;
struct node *left, *right;
};
// A utility function to create a new BST node
struct node *newNode(int item)
{
struct node *temp = new node;
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
// A utility function to do preorder traversal of BST
void preorder(struct node *root)
{
if (root != NULL)
{
cout << root->key << " ";
preorder(root->left);
preorder(root->right);
}
}
// function for constructing trees
vector constructTrees(int start, int end)
{
vector list;
/* if start > end then subtree will be empty so returning NULL
in the list */
if (start > end)
{
list.push_back(NULL);
return list;
}
/* iterating through all values from start to end for constructing
left and right subtree recursively */
for (int i = start; i <= end; i++)
{
/* constructing left subtree */
vector leftSubtree = constructTrees(start, i - 1);
/* constructing right subtree */
vector rightSubtree = constructTrees(i + 1, end);
/* now looping through all left and right subtrees and connecting
them to ith root below */
for (int j = 0; j < leftSubtree.size(); j++)
{
struct node* left = leftSubtree[j];
for (int k = 0; k < rightSubtree.size(); k++)
{
struct node * right = rightSubtree[k];
struct node * node = newNode(i);// making value i as root
node->left = left; // connect left subtree
node->right = right; // connect right subtree
list.push_back(node); // add this tree to list
}
}
}
return list;
}
// Driver Program to test above functions
int main()
{
// Construct all possible BSTs
vector totalTreesFrom1toN = constructTrees(1, 3);
/* Printing preorder traversal of all constructed BSTs */
cout << "Preorder traversals of all constructed BSTs are  ";
for (int i = 0; i < totalTreesFrom1toN.size(); i++)
{
preorder(totalTreesFrom1toN[i]);
cout << endl;
}
return 0;
}
Output:
Ad

More Related Content

Similar to Write a function in C++ to generate an N-node random binary search t.pdf (20)

A)B) C++ program to create a Complete Binary tree from its Lin.pdf
A)B) C++ program to create a Complete Binary tree from its Lin.pdfA)B) C++ program to create a Complete Binary tree from its Lin.pdf
A)B) C++ program to create a Complete Binary tree from its Lin.pdf
anton291
 
Link List Programming Linked List in Cpp
Link List Programming Linked List in CppLink List Programming Linked List in Cpp
Link List Programming Linked List in Cpp
Anil Yadav
 
THE CODE HAS A SEGMENTATION FAULT BUT I CANNOT FIND OUT WHERE. NEED .pdf
THE CODE HAS A SEGMENTATION FAULT BUT I CANNOT FIND OUT WHERE. NEED .pdfTHE CODE HAS A SEGMENTATION FAULT BUT I CANNOT FIND OUT WHERE. NEED .pdf
THE CODE HAS A SEGMENTATION FAULT BUT I CANNOT FIND OUT WHERE. NEED .pdf
fathimahardwareelect
 
How to build a Linked List that can insert any type of data. For exa.pdf
How to build a Linked List that can insert any type of data. For exa.pdfHow to build a Linked List that can insert any type of data. For exa.pdf
How to build a Linked List that can insert any type of data. For exa.pdf
arpittradersjdr
 
DSA(1).pptx
DSA(1).pptxDSA(1).pptx
DSA(1).pptx
DaniyalAli81
 
Doublylinklist
DoublylinklistDoublylinklist
Doublylinklist
ritu1806
 
DAA Lab Work.docx
DAA Lab Work.docxDAA Lab Work.docx
DAA Lab Work.docx
Deepusri2000Srivasta
 
write recursive function that calculates and returns the length of a.pdf
write recursive function that calculates and returns the length of a.pdfwrite recursive function that calculates and returns the length of a.pdf
write recursive function that calculates and returns the length of a.pdf
arpitcomputronics
 
#includeiostream#includecstdio#includecstdlibusing names.pdf
#includeiostream#includecstdio#includecstdlibusing names.pdf#includeiostream#includecstdio#includecstdlibusing names.pdf
#includeiostream#includecstdio#includecstdlibusing names.pdf
KUNALHARCHANDANI1
 
Introduction---to-Expression---Trees.pdf
Introduction---to-Expression---Trees.pdfIntroduction---to-Expression---Trees.pdf
Introduction---to-Expression---Trees.pdf
khetyidris
 
Using the provided table interface table.h and the sample linked lis.pdf
Using the provided table interface table.h and the sample linked lis.pdfUsing the provided table interface table.h and the sample linked lis.pdf
Using the provided table interface table.h and the sample linked lis.pdf
connellalykshamesb60
 
This assignment and the next (#5) involve design and development of a.pdf
This assignment and the next (#5) involve design and development of a.pdfThis assignment and the next (#5) involve design and development of a.pdf
This assignment and the next (#5) involve design and development of a.pdf
EricvtJFraserr
 
Lab Week 2 Game Programming.docx
Lab Week 2 Game Programming.docxLab Week 2 Game Programming.docx
Lab Week 2 Game Programming.docx
teyaj1
 
I have C++ question that I do not know how to do, Can you teach me t.pdf
I have C++ question that I do not know how to do, Can you teach me t.pdfI have C++ question that I do not know how to do, Can you teach me t.pdf
I have C++ question that I do not know how to do, Can you teach me t.pdf
fasttrackscardecors
 
Write a C++ function that delete nodes in a doubly linkedlist- It shou.docx
Write a C++ function that delete nodes in a doubly linkedlist- It shou.docxWrite a C++ function that delete nodes in a doubly linkedlist- It shou.docx
Write a C++ function that delete nodes in a doubly linkedlist- It shou.docx
noreendchesterton753
 
Use C++ Write a function to merge two doubly linked lists. The input.pdf
Use C++ Write a function to merge two doubly linked lists. The input.pdfUse C++ Write a function to merge two doubly linked lists. The input.pdf
Use C++ Write a function to merge two doubly linked lists. The input.pdf
shalins6
 
take the following code and give details of what each line of code i.pdf
take the following code and give details of what each line of code i.pdftake the following code and give details of what each line of code i.pdf
take the following code and give details of what each line of code i.pdf
fastechsrv
 
C++ Please write the whole code that is needed for this assignment- wr.docx
C++ Please write the whole code that is needed for this assignment- wr.docxC++ Please write the whole code that is needed for this assignment- wr.docx
C++ Please write the whole code that is needed for this assignment- wr.docx
BrianGHiNewmanv
 
Once you have all the structures working as intended- it is time to co.docx
Once you have all the structures working as intended- it is time to co.docxOnce you have all the structures working as intended- it is time to co.docx
Once you have all the structures working as intended- it is time to co.docx
farrahkur54
 
Write a program to implement below operations with both singly and d.pdf
Write a program to implement below operations with both singly and d.pdfWrite a program to implement below operations with both singly and d.pdf
Write a program to implement below operations with both singly and d.pdf
thangarajarivukadal
 
A)B) C++ program to create a Complete Binary tree from its Lin.pdf
A)B) C++ program to create a Complete Binary tree from its Lin.pdfA)B) C++ program to create a Complete Binary tree from its Lin.pdf
A)B) C++ program to create a Complete Binary tree from its Lin.pdf
anton291
 
Link List Programming Linked List in Cpp
Link List Programming Linked List in CppLink List Programming Linked List in Cpp
Link List Programming Linked List in Cpp
Anil Yadav
 
THE CODE HAS A SEGMENTATION FAULT BUT I CANNOT FIND OUT WHERE. NEED .pdf
THE CODE HAS A SEGMENTATION FAULT BUT I CANNOT FIND OUT WHERE. NEED .pdfTHE CODE HAS A SEGMENTATION FAULT BUT I CANNOT FIND OUT WHERE. NEED .pdf
THE CODE HAS A SEGMENTATION FAULT BUT I CANNOT FIND OUT WHERE. NEED .pdf
fathimahardwareelect
 
How to build a Linked List that can insert any type of data. For exa.pdf
How to build a Linked List that can insert any type of data. For exa.pdfHow to build a Linked List that can insert any type of data. For exa.pdf
How to build a Linked List that can insert any type of data. For exa.pdf
arpittradersjdr
 
Doublylinklist
DoublylinklistDoublylinklist
Doublylinklist
ritu1806
 
write recursive function that calculates and returns the length of a.pdf
write recursive function that calculates and returns the length of a.pdfwrite recursive function that calculates and returns the length of a.pdf
write recursive function that calculates and returns the length of a.pdf
arpitcomputronics
 
#includeiostream#includecstdio#includecstdlibusing names.pdf
#includeiostream#includecstdio#includecstdlibusing names.pdf#includeiostream#includecstdio#includecstdlibusing names.pdf
#includeiostream#includecstdio#includecstdlibusing names.pdf
KUNALHARCHANDANI1
 
Introduction---to-Expression---Trees.pdf
Introduction---to-Expression---Trees.pdfIntroduction---to-Expression---Trees.pdf
Introduction---to-Expression---Trees.pdf
khetyidris
 
Using the provided table interface table.h and the sample linked lis.pdf
Using the provided table interface table.h and the sample linked lis.pdfUsing the provided table interface table.h and the sample linked lis.pdf
Using the provided table interface table.h and the sample linked lis.pdf
connellalykshamesb60
 
This assignment and the next (#5) involve design and development of a.pdf
This assignment and the next (#5) involve design and development of a.pdfThis assignment and the next (#5) involve design and development of a.pdf
This assignment and the next (#5) involve design and development of a.pdf
EricvtJFraserr
 
Lab Week 2 Game Programming.docx
Lab Week 2 Game Programming.docxLab Week 2 Game Programming.docx
Lab Week 2 Game Programming.docx
teyaj1
 
I have C++ question that I do not know how to do, Can you teach me t.pdf
I have C++ question that I do not know how to do, Can you teach me t.pdfI have C++ question that I do not know how to do, Can you teach me t.pdf
I have C++ question that I do not know how to do, Can you teach me t.pdf
fasttrackscardecors
 
Write a C++ function that delete nodes in a doubly linkedlist- It shou.docx
Write a C++ function that delete nodes in a doubly linkedlist- It shou.docxWrite a C++ function that delete nodes in a doubly linkedlist- It shou.docx
Write a C++ function that delete nodes in a doubly linkedlist- It shou.docx
noreendchesterton753
 
Use C++ Write a function to merge two doubly linked lists. The input.pdf
Use C++ Write a function to merge two doubly linked lists. The input.pdfUse C++ Write a function to merge two doubly linked lists. The input.pdf
Use C++ Write a function to merge two doubly linked lists. The input.pdf
shalins6
 
take the following code and give details of what each line of code i.pdf
take the following code and give details of what each line of code i.pdftake the following code and give details of what each line of code i.pdf
take the following code and give details of what each line of code i.pdf
fastechsrv
 
C++ Please write the whole code that is needed for this assignment- wr.docx
C++ Please write the whole code that is needed for this assignment- wr.docxC++ Please write the whole code that is needed for this assignment- wr.docx
C++ Please write the whole code that is needed for this assignment- wr.docx
BrianGHiNewmanv
 
Once you have all the structures working as intended- it is time to co.docx
Once you have all the structures working as intended- it is time to co.docxOnce you have all the structures working as intended- it is time to co.docx
Once you have all the structures working as intended- it is time to co.docx
farrahkur54
 
Write a program to implement below operations with both singly and d.pdf
Write a program to implement below operations with both singly and d.pdfWrite a program to implement below operations with both singly and d.pdf
Write a program to implement below operations with both singly and d.pdf
thangarajarivukadal
 

More from info824691 (20)

In what ways are humans also primatesSolutionBoth humans and .pdf
In what ways are humans also primatesSolutionBoth humans and .pdfIn what ways are humans also primatesSolutionBoth humans and .pdf
In what ways are humans also primatesSolutionBoth humans and .pdf
info824691
 
i need Understand the role of capillaries in fluidnutrient exchange.pdf
i need Understand the role of capillaries in fluidnutrient exchange.pdfi need Understand the role of capillaries in fluidnutrient exchange.pdf
i need Understand the role of capillaries in fluidnutrient exchange.pdf
info824691
 
Give an explanation of the trait below. SolutionIt is dominant.pdf
Give an explanation of the trait below.  SolutionIt is dominant.pdfGive an explanation of the trait below.  SolutionIt is dominant.pdf
Give an explanation of the trait below. SolutionIt is dominant.pdf
info824691
 
External decision makers would look primarily to financial accounting.pdf
External decision makers would look primarily to financial accounting.pdfExternal decision makers would look primarily to financial accounting.pdf
External decision makers would look primarily to financial accounting.pdf
info824691
 
ecosystem ecologyTheme Physical Template of Terrestrial Environme.pdf
ecosystem ecologyTheme Physical Template of Terrestrial Environme.pdfecosystem ecologyTheme Physical Template of Terrestrial Environme.pdf
ecosystem ecologyTheme Physical Template of Terrestrial Environme.pdf
info824691
 
Distribution of Resources Whether a resource is distributed evenly a.pdf
Distribution of Resources  Whether a resource is distributed evenly a.pdfDistribution of Resources  Whether a resource is distributed evenly a.pdf
Distribution of Resources Whether a resource is distributed evenly a.pdf
info824691
 
Describe the mechanism of action of drugs effective against viral in.pdf
Describe the mechanism of action of drugs effective against viral in.pdfDescribe the mechanism of action of drugs effective against viral in.pdf
Describe the mechanism of action of drugs effective against viral in.pdf
info824691
 
During Mitosis and Meiosis, describe how and where errors might be m.pdf
During Mitosis and Meiosis, describe how and where errors might be m.pdfDuring Mitosis and Meiosis, describe how and where errors might be m.pdf
During Mitosis and Meiosis, describe how and where errors might be m.pdf
info824691
 
Define indirect finance, direct finance, debt, and equity.Solut.pdf
Define indirect finance, direct finance, debt, and equity.Solut.pdfDefine indirect finance, direct finance, debt, and equity.Solut.pdf
Define indirect finance, direct finance, debt, and equity.Solut.pdf
info824691
 
Chapter 17 True False Questions 1. Hemostasis is the production of fo.pdf
Chapter 17 True False Questions 1. Hemostasis is the production of fo.pdfChapter 17 True False Questions 1. Hemostasis is the production of fo.pdf
Chapter 17 True False Questions 1. Hemostasis is the production of fo.pdf
info824691
 
An object is placed 12.9 cm in front of the cornea. (The cornea is t.pdf
An object is placed 12.9 cm in front of the cornea. (The cornea is t.pdfAn object is placed 12.9 cm in front of the cornea. (The cornea is t.pdf
An object is placed 12.9 cm in front of the cornea. (The cornea is t.pdf
info824691
 
An archaeal contaminant is discovered in a shipment of sausages. To .pdf
An archaeal contaminant is discovered in a shipment of sausages. To .pdfAn archaeal contaminant is discovered in a shipment of sausages. To .pdf
An archaeal contaminant is discovered in a shipment of sausages. To .pdf
info824691
 
8. A box of parts contains 8 good items and 2 defective items. If 2 .pdf
8. A box of parts contains 8 good items and 2 defective items. If 2 .pdf8. A box of parts contains 8 good items and 2 defective items. If 2 .pdf
8. A box of parts contains 8 good items and 2 defective items. If 2 .pdf
info824691
 
A microbiologist obtains two samples one of a virus and the other of.pdf
A microbiologist obtains two samples one of a virus and the other of.pdfA microbiologist obtains two samples one of a virus and the other of.pdf
A microbiologist obtains two samples one of a virus and the other of.pdf
info824691
 
Can someone please explain part E to me. Its the only one I dont.pdf
Can someone please explain part E to me. Its the only one I dont.pdfCan someone please explain part E to me. Its the only one I dont.pdf
Can someone please explain part E to me. Its the only one I dont.pdf
info824691
 
A two-way ANOVA with interaction has how many sources of variation.pdf
A two-way ANOVA with interaction has how many sources of variation.pdfA two-way ANOVA with interaction has how many sources of variation.pdf
A two-way ANOVA with interaction has how many sources of variation.pdf
info824691
 
2. Start capturing packets then open a webpage. a. “Follow” the TCP .pdf
2. Start capturing packets then open a webpage. a. “Follow” the TCP .pdf2. Start capturing packets then open a webpage. a. “Follow” the TCP .pdf
2. Start capturing packets then open a webpage. a. “Follow” the TCP .pdf
info824691
 
Bioinformatics sequencing excercise. Sequencing the human genome sta.pdf
Bioinformatics sequencing excercise. Sequencing the human genome sta.pdfBioinformatics sequencing excercise. Sequencing the human genome sta.pdf
Bioinformatics sequencing excercise. Sequencing the human genome sta.pdf
info824691
 
Write a paragraph introducing the immunology pertaining to Crohns D.pdf
Write a paragraph introducing the immunology pertaining to Crohns D.pdfWrite a paragraph introducing the immunology pertaining to Crohns D.pdf
Write a paragraph introducing the immunology pertaining to Crohns D.pdf
info824691
 
Why arent conjugative plasmids degraded by Restriction-Modificatio.pdf
Why arent conjugative plasmids degraded by Restriction-Modificatio.pdfWhy arent conjugative plasmids degraded by Restriction-Modificatio.pdf
Why arent conjugative plasmids degraded by Restriction-Modificatio.pdf
info824691
 
In what ways are humans also primatesSolutionBoth humans and .pdf
In what ways are humans also primatesSolutionBoth humans and .pdfIn what ways are humans also primatesSolutionBoth humans and .pdf
In what ways are humans also primatesSolutionBoth humans and .pdf
info824691
 
i need Understand the role of capillaries in fluidnutrient exchange.pdf
i need Understand the role of capillaries in fluidnutrient exchange.pdfi need Understand the role of capillaries in fluidnutrient exchange.pdf
i need Understand the role of capillaries in fluidnutrient exchange.pdf
info824691
 
Give an explanation of the trait below. SolutionIt is dominant.pdf
Give an explanation of the trait below.  SolutionIt is dominant.pdfGive an explanation of the trait below.  SolutionIt is dominant.pdf
Give an explanation of the trait below. SolutionIt is dominant.pdf
info824691
 
External decision makers would look primarily to financial accounting.pdf
External decision makers would look primarily to financial accounting.pdfExternal decision makers would look primarily to financial accounting.pdf
External decision makers would look primarily to financial accounting.pdf
info824691
 
ecosystem ecologyTheme Physical Template of Terrestrial Environme.pdf
ecosystem ecologyTheme Physical Template of Terrestrial Environme.pdfecosystem ecologyTheme Physical Template of Terrestrial Environme.pdf
ecosystem ecologyTheme Physical Template of Terrestrial Environme.pdf
info824691
 
Distribution of Resources Whether a resource is distributed evenly a.pdf
Distribution of Resources  Whether a resource is distributed evenly a.pdfDistribution of Resources  Whether a resource is distributed evenly a.pdf
Distribution of Resources Whether a resource is distributed evenly a.pdf
info824691
 
Describe the mechanism of action of drugs effective against viral in.pdf
Describe the mechanism of action of drugs effective against viral in.pdfDescribe the mechanism of action of drugs effective against viral in.pdf
Describe the mechanism of action of drugs effective against viral in.pdf
info824691
 
During Mitosis and Meiosis, describe how and where errors might be m.pdf
During Mitosis and Meiosis, describe how and where errors might be m.pdfDuring Mitosis and Meiosis, describe how and where errors might be m.pdf
During Mitosis and Meiosis, describe how and where errors might be m.pdf
info824691
 
Define indirect finance, direct finance, debt, and equity.Solut.pdf
Define indirect finance, direct finance, debt, and equity.Solut.pdfDefine indirect finance, direct finance, debt, and equity.Solut.pdf
Define indirect finance, direct finance, debt, and equity.Solut.pdf
info824691
 
Chapter 17 True False Questions 1. Hemostasis is the production of fo.pdf
Chapter 17 True False Questions 1. Hemostasis is the production of fo.pdfChapter 17 True False Questions 1. Hemostasis is the production of fo.pdf
Chapter 17 True False Questions 1. Hemostasis is the production of fo.pdf
info824691
 
An object is placed 12.9 cm in front of the cornea. (The cornea is t.pdf
An object is placed 12.9 cm in front of the cornea. (The cornea is t.pdfAn object is placed 12.9 cm in front of the cornea. (The cornea is t.pdf
An object is placed 12.9 cm in front of the cornea. (The cornea is t.pdf
info824691
 
An archaeal contaminant is discovered in a shipment of sausages. To .pdf
An archaeal contaminant is discovered in a shipment of sausages. To .pdfAn archaeal contaminant is discovered in a shipment of sausages. To .pdf
An archaeal contaminant is discovered in a shipment of sausages. To .pdf
info824691
 
8. A box of parts contains 8 good items and 2 defective items. If 2 .pdf
8. A box of parts contains 8 good items and 2 defective items. If 2 .pdf8. A box of parts contains 8 good items and 2 defective items. If 2 .pdf
8. A box of parts contains 8 good items and 2 defective items. If 2 .pdf
info824691
 
A microbiologist obtains two samples one of a virus and the other of.pdf
A microbiologist obtains two samples one of a virus and the other of.pdfA microbiologist obtains two samples one of a virus and the other of.pdf
A microbiologist obtains two samples one of a virus and the other of.pdf
info824691
 
Can someone please explain part E to me. Its the only one I dont.pdf
Can someone please explain part E to me. Its the only one I dont.pdfCan someone please explain part E to me. Its the only one I dont.pdf
Can someone please explain part E to me. Its the only one I dont.pdf
info824691
 
A two-way ANOVA with interaction has how many sources of variation.pdf
A two-way ANOVA with interaction has how many sources of variation.pdfA two-way ANOVA with interaction has how many sources of variation.pdf
A two-way ANOVA with interaction has how many sources of variation.pdf
info824691
 
2. Start capturing packets then open a webpage. a. “Follow” the TCP .pdf
2. Start capturing packets then open a webpage. a. “Follow” the TCP .pdf2. Start capturing packets then open a webpage. a. “Follow” the TCP .pdf
2. Start capturing packets then open a webpage. a. “Follow” the TCP .pdf
info824691
 
Bioinformatics sequencing excercise. Sequencing the human genome sta.pdf
Bioinformatics sequencing excercise. Sequencing the human genome sta.pdfBioinformatics sequencing excercise. Sequencing the human genome sta.pdf
Bioinformatics sequencing excercise. Sequencing the human genome sta.pdf
info824691
 
Write a paragraph introducing the immunology pertaining to Crohns D.pdf
Write a paragraph introducing the immunology pertaining to Crohns D.pdfWrite a paragraph introducing the immunology pertaining to Crohns D.pdf
Write a paragraph introducing the immunology pertaining to Crohns D.pdf
info824691
 
Why arent conjugative plasmids degraded by Restriction-Modificatio.pdf
Why arent conjugative plasmids degraded by Restriction-Modificatio.pdfWhy arent conjugative plasmids degraded by Restriction-Modificatio.pdf
Why arent conjugative plasmids degraded by Restriction-Modificatio.pdf
info824691
 
Ad

Recently uploaded (20)

LDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living WorkshopLDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDM Mia eStudios
 
How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18
Celine George
 
Drugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdfDrugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdf
crewot855
 
What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)
jemille6
 
Overview Well-Being and Creative Careers
Overview Well-Being and Creative CareersOverview Well-Being and Creative Careers
Overview Well-Being and Creative Careers
University of Amsterdam
 
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
parmarjuli1412
 
spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)
Mohamed Rizk Khodair
 
puzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tensepuzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tense
OlgaLeonorTorresSnch
 
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Leonel Morgado
 
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
Dr. Nasir Mustafa
 
All About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdfAll About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdf
TechSoup
 
Form View Attributes in Odoo 18 - Odoo Slides
Form View Attributes in Odoo 18 - Odoo SlidesForm View Attributes in Odoo 18 - Odoo Slides
Form View Attributes in Odoo 18 - Odoo Slides
Celine George
 
Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...
parmarjuli1412
 
Cultivation Practice of Onion in Nepal.pptx
Cultivation Practice of Onion in Nepal.pptxCultivation Practice of Onion in Nepal.pptx
Cultivation Practice of Onion in Nepal.pptx
UmeshTimilsina1
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
Nguyen Thanh Tu Collection
 
Origin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theoriesOrigin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theories
PrachiSontakke5
 
Ancient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian HistoryAncient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian History
Virag Sontakke
 
Myasthenia gravis (Neuromuscular disorder)
Myasthenia gravis (Neuromuscular disorder)Myasthenia gravis (Neuromuscular disorder)
Myasthenia gravis (Neuromuscular disorder)
Mohamed Rizk Khodair
 
CNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscessCNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscess
Mohamed Rizk Khodair
 
Search Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo SlidesSearch Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo Slides
Celine George
 
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living WorkshopLDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDM Mia eStudios
 
How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18
Celine George
 
Drugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdfDrugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdf
crewot855
 
What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)
jemille6
 
Overview Well-Being and Creative Careers
Overview Well-Being and Creative CareersOverview Well-Being and Creative Careers
Overview Well-Being and Creative Careers
University of Amsterdam
 
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
parmarjuli1412
 
spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)
Mohamed Rizk Khodair
 
puzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tensepuzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tense
OlgaLeonorTorresSnch
 
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Leonel Morgado
 
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
Dr. Nasir Mustafa
 
All About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdfAll About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdf
TechSoup
 
Form View Attributes in Odoo 18 - Odoo Slides
Form View Attributes in Odoo 18 - Odoo SlidesForm View Attributes in Odoo 18 - Odoo Slides
Form View Attributes in Odoo 18 - Odoo Slides
Celine George
 
Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...
parmarjuli1412
 
Cultivation Practice of Onion in Nepal.pptx
Cultivation Practice of Onion in Nepal.pptxCultivation Practice of Onion in Nepal.pptx
Cultivation Practice of Onion in Nepal.pptx
UmeshTimilsina1
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
Nguyen Thanh Tu Collection
 
Origin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theoriesOrigin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theories
PrachiSontakke5
 
Ancient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian HistoryAncient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian History
Virag Sontakke
 
Myasthenia gravis (Neuromuscular disorder)
Myasthenia gravis (Neuromuscular disorder)Myasthenia gravis (Neuromuscular disorder)
Myasthenia gravis (Neuromuscular disorder)
Mohamed Rizk Khodair
 
CNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscessCNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscess
Mohamed Rizk Khodair
 
Search Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo SlidesSearch Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo Slides
Celine George
 
Ad

Write a function in C++ to generate an N-node random binary search t.pdf

  • 1. Write a function in C++ to generate an N-node random binary search tree with distinct keys 1 through N. Assume that you have available a function, randInt(lower,upper), that generates a uniform random integer in the appropriate closed interval. What is the running time of your routine? Solution / A C++ prgroam to contrcut all unique BSTs for keys from 1 to n #include #include using namespace std; // node structure struct node { int key; struct node *left, *right; }; // A utility function to create a new BST node struct node *newNode(int item) { struct node *temp = new node; temp->key = item; temp->left = temp->right = NULL; return temp; } // A utility function to do preorder traversal of BST void preorder(struct node *root) { if (root != NULL) { cout << root->key << " "; preorder(root->left); preorder(root->right); }
  • 2. } // function for constructing trees vector constructTrees(int start, int end) { vector list; /* if start > end then subtree will be empty so returning NULL in the list */ if (start > end) { list.push_back(NULL); return list; } /* iterating through all values from start to end for constructing left and right subtree recursively */ for (int i = start; i <= end; i++) { /* constructing left subtree */ vector leftSubtree = constructTrees(start, i - 1); /* constructing right subtree */ vector rightSubtree = constructTrees(i + 1, end); /* now looping through all left and right subtrees and connecting them to ith root below */ for (int j = 0; j < leftSubtree.size(); j++) { struct node* left = leftSubtree[j]; for (int k = 0; k < rightSubtree.size(); k++) { struct node * right = rightSubtree[k]; struct node * node = newNode(i);// making value i as root node->left = left; // connect left subtree node->right = right; // connect right subtree list.push_back(node); // add this tree to list } } } return list;
  • 3. } // Driver Program to test above functions int main() { // Construct all possible BSTs vector totalTreesFrom1toN = constructTrees(1, 3); /* Printing preorder traversal of all constructed BSTs */ cout << "Preorder traversals of all constructed BSTs are "; for (int i = 0; i < totalTreesFrom1toN.size(); i++) { preorder(totalTreesFrom1toN[i]); cout << endl; } return 0; } Output:
  翻译: