SlideShare a Scribd company logo
1 of 3
Download to read offline
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:

More Related Content

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

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 .pdffathimahardwareelect
 
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.pdfarpittradersjdr
 
Doublylinklist
DoublylinklistDoublylinklist
Doublylinklistritu1806
 
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.pdfarpitcomputronics
 
#includeiostream#includecstdio#includecstdlibusing names.pdf
#includeiostream#includecstdio#includecstdlibusing names.pdf#includeiostream#includecstdio#includecstdlibusing names.pdf
#includeiostream#includecstdio#includecstdlibusing names.pdfKUNALHARCHANDANI1
 
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.pdfconnellalykshamesb60
 
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.pdfEricvtJFraserr
 
Lab Week 2 Game Programming.docx
Lab Week 2 Game Programming.docxLab Week 2 Game Programming.docx
Lab Week 2 Game Programming.docxteyaj1
 
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.pdffasttrackscardecors
 
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.docxnoreendchesterton753
 
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.pdfshalins6
 
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.pdffastechsrv
 
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.docxBrianGHiNewmanv
 
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.docxfarrahkur54
 
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.pdfthangarajarivukadal
 
C++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdf
C++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdfC++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdf
C++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdfpoblettesedanoree498
 
This is problem is same problem which i submitted on 22017, I just.pdf
This is problem is same problem which i submitted on 22017, I just.pdfThis is problem is same problem which i submitted on 22017, I just.pdf
This is problem is same problem which i submitted on 22017, I just.pdffcaindore
 
Need Help with this Java Assignment. Program should be done in JAVA .pdf
Need Help with this Java Assignment. Program should be done in JAVA .pdfNeed Help with this Java Assignment. Program should be done in JAVA .pdf
Need Help with this Java Assignment. Program should be done in JAVA .pdfarchiesgallery
 

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

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
 
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
 
DSA(1).pptx
DSA(1).pptxDSA(1).pptx
DSA(1).pptx
 
Doublylinklist
DoublylinklistDoublylinklist
Doublylinklist
 
DAA Lab Work.docx
DAA Lab Work.docxDAA Lab Work.docx
DAA Lab Work.docx
 
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
 
#includeiostream#includecstdio#includecstdlibusing names.pdf
#includeiostream#includecstdio#includecstdlibusing names.pdf#includeiostream#includecstdio#includecstdlibusing names.pdf
#includeiostream#includecstdio#includecstdlibusing names.pdf
 
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
 
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
 
Lab Week 2 Game Programming.docx
Lab Week 2 Game Programming.docxLab Week 2 Game Programming.docx
Lab Week 2 Game Programming.docx
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 
C++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdf
C++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdfC++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdf
C++ Doubly-Linked ListsThe goal of the exercise is to implement a.pdf
 
This is problem is same problem which i submitted on 22017, I just.pdf
This is problem is same problem which i submitted on 22017, I just.pdfThis is problem is same problem which i submitted on 22017, I just.pdf
This is problem is same problem which i submitted on 22017, I just.pdf
 
Need Help with this Java Assignment. Program should be done in JAVA .pdf
Need Help with this Java Assignment. Program should be done in JAVA .pdfNeed Help with this Java Assignment. Program should be done in JAVA .pdf
Need Help with this Java Assignment. Program should be done in JAVA .pdf
 

More from 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 .pdfinfo824691
 
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.pdfinfo824691
 
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.pdfinfo824691
 
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.pdfinfo824691
 
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.pdfinfo824691
 
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.pdfinfo824691
 
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.pdfinfo824691
 
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.pdfinfo824691
 
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.pdfinfo824691
 
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.pdfinfo824691
 
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.pdfinfo824691
 
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 .pdfinfo824691
 
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 .pdfinfo824691
 
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.pdfinfo824691
 
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.pdfinfo824691
 
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.pdfinfo824691
 
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 .pdfinfo824691
 
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.pdfinfo824691
 
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.pdfinfo824691
 
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.pdfinfo824691
 

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
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 

Recently uploaded

Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Association for Project Management
 
Third Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxThird Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxAmita Gupta
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxcallscotland1987
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docxPoojaSen20
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxdhanalakshmis0310
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 

Recently uploaded (20)

Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Third Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxThird Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptx
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 

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: