SlideShare a Scribd company logo
1 of 7
Download to read offline
main.cpp
#include "TreeNode.h"
//GIVEN
void inorderTraversal(TreeNode * root);
//TODO
TreeNode * search(TreeNode * node,int data);
//GIVEN
void insert(TreeNode * node,int data);
//GIVEN
bool isNull(TreeNode * node){
return node==nullptr;
}
int main() {
// create the root, gets set to null
TreeNode * root;
// create the roor and set the data of root to 5
root= new TreeNode(5);
//create two additional nodes with data values 10 and 3
// these will go to the right and left of root respectively
TreeNode * ten= new TreeNode(10);
TreeNode * three= new TreeNode(3);
//connect ten to the right of root (which has data 5)
root->setRight(ten);
//connect three to the left of root (which has data 5)
root->setLeft(three);
// note this can also be done as
//root.setRight(new TreeNode(10));
//root.setLeft(new TreeNode(3);)
// add two more nodes
//the first has data value 7. So to keep the tree in insorted order, it should get attached as the left
node of ten
// the second has data value 4. So to keep the tree in insorted order, it should get attached as the
right node of three
ten->addLeft(7);
three->addRight(4);
std::cout<<"**************************************n";
std::cout<<"Printing the Inorder Traversaln";
inorderTraversal(root);
std::cout<<"**************************************n";
std::cout<<"Searching for Node n";
TreeNode* result = search(root,4);
if (result!=nullptr){
std::cout<<"Found "<getData()<<"n";
}
else
std::cout<<"Not Found "<<4<<"n";
result = search(root,1);
if (result!=nullptr){
std::cout<<"Found "<getData()<<"n";
}
else
std::cout<<"Not Found "<<1<<"n";
std::cout<<"**************************************n";
std::cout<<"Inserting 6n";
insert(root,6);
std::cout<<"**************************************n";
std::cout<<"Printing the Inorder Traversaln";
inorderTraversal(root);
}
// uses recursion
void inorderTraversal(TreeNode * node){
// exit case
if (isNull(node)) return;
if (node->isLeaf()){
std::cout<<"Printing Leaf Node "<getData()<<"n";
return;}
// reached a node with no left, so print the node and travel right
if (!isNull(node->getLeft()))
// if there is a left path, then travel further on that
inorderTraversal(node->getLeft());
std::cout<<"Printing Node "<getData()<<"n";
// save and travel the right path of the current node being processed
inorderTraversal(node->getRight());
}
// uses recursion
//TODO
TreeNode * search(TreeNode * node, int data){
// if the node is null return the null ptr
//if this nodes data equals the search date return found
// if not, if the left tree exists and search data less than
//this nodes data return the result of recursive all to search with left pointer
// if no left tree, but right tree exists and search data greater than
//this nodes data return the result of recursive all to search with right pointer
// if both above conditions not true return null ptr
}
//uses recursion
void insert(TreeNode * node,int data){
if (node->getData()==data)
return;
else if(datagetData()){
if (!isNull(node->getLeft()))
// std::cout<<"Going Left from "<getData()<<"n";
return insert(node->getLeft(),data);
else node->setLeft(new TreeNode(data));
}
else if (data>node->getData()){
if (!isNull(node->getRight()))
return insert(node->getRight(),data);
else node->setRight(new TreeNode(data));
}
}
TreeNode.cpp
#include "TreeNode.h"
TreeNode::TreeNode(){
data=0;
left=nullptr;
right=nullptr;
}
TreeNode::TreeNode(int data){
this->data=data;
this->left=nullptr;
this->right=nullptr;
}
TreeNode::TreeNode(int data,TreeNode * left, TreeNode * right){
this->data=data;
this->left=left;
this->right=right;
}
void TreeNode::setData(int data){
this->data=data;
}
int TreeNode::getData(){
return data;
}
//TODO
TreeNode * TreeNode::getLeft(){
//
}
TreeNode * TreeNode::getRight(){
return right;
}
// does not create any new node. Just sets the right pointer
void TreeNode::setRight(TreeNode *newRight){
right=newRight;
}
// does not create any new node. Just sets the left pointer
//TODO
void TreeNode::setLeft(TreeNode *newLeft){
//
}
bool TreeNode::isLeaf(){
return (left==nullptr&&right==nullptr);
}
//creates a new node with the data value and sets the rightpointer to it
void TreeNode::addRight(int data){
right= new TreeNode(data,nullptr,nullptr);
}
//creates a new node with the data value and sets the left pointer to it
//TODO
void TreeNode::addLeft(int data){
//
}
TreeNode.h
#include
#include
#include
class TreeNode{
private: int data;
private: TreeNode * left;
private: TreeNode * right;
public:
TreeNode();
TreeNode(int data);
TreeNode(int data, TreeNode * left, TreeNode * right);
void setData(int data);
int getData();
bool isLeaf();
TreeNode * getLeft();
TreeNode * getRight();
void setRight(TreeNode *newRight);
void setLeft(TreeNode *newLeft);
void addRight(int data);
void addLeft(int data);
};
Make sure that the completed code would display the below output:
**************************************
Printing the Inorder Traversal
Printing Node 3
Printing Leaf Node 4
Printing Node 5
Printing Leaf Node 7
Printing Node 10
**************************************
Searching for Node
Found 4
Not Found 1
**************************************
Inserting 6
**************************************
Printing the Inorder Traversal
Printing Node 3
Printing Leaf Node 4
Printing Node 5
Printing Leaf Node 6
Printing Node 7
Printing Node 10 Description You are given a template that contains the TreeNode class header
and partially implemented TreeNode.cpp file. A driver is also included. This driver constructs
TreeNode objects and connects their pointers, manually creating a sorted binary tree. Methods to
insert nodes while keeping the tree sorted is implemented as also to traverse the tree "inorder". A
search method that traverses the tree to search for a given data value needs to be written.
Recursion is used in all these methods. The output file is also given to you TreeNode private: int
data; private: TreeNode * left; private: TreeNode * right; public: TreeNode(); //default
constructor: sets data to 0, pointers to nullptr TreeNode(int data); //custom constructor: sets this
data to data, pointers to nullptr TreeNode(int data, TreeNode * left, TreeNode * right); custom
constructor, sets data and pointers void setData(int data); // sets data int getData(); // returns data
bool isLeaf(); // returns true if both pointers are null. TreeNode * getLeft(); // returns left Pointer
TreeNode * getRight(); //returns left Pointer void setRight(TreeNode *newRight); sets right
Pointer void setLeft(TreeNode *newLeft); sets left Pointer void addRight(int data); adds a new
TreeNode with this data to the right of current TreeNode void addLeft(int data); adds a new
TreeNode with this data to the left of current TreeNode };
Most of these methods have been implemented. Please implement the "right" methods by
examining the "left" methods TreeNode * getLeft(); // returns left Pointer void setLeft(TreeNode
*newLeft); sets left Pointer void addLeft(int data); adds a new TreeNode with this data to the left
of current TreeNode
# The driver is given is given to you that does the following 1. Creates a root TreeNode with
data value 5 2. Create two additional nodes with data values 10 and 3 3. Set these to the right and
left of root respectively 4. Add two more nodes- the first has data value 7. So to keep the tree in
insorted order, it should get attached as the left node of ten 5. Add the second node with data
value 4 . So to keep the tree in insorted order, it should get attached as the right node of three 6.
Call the inorderTraversal methods that traverses the tree starting from the root, in sorted order
and prints the nodes visited.
7. Search for an existing node with data value 4 . 8. Search for a non existing node with data
value 1. 9. Insert a new node with data value 6 . 10. Call the inorderTraversal methods that
traverses the tree starting from the root, in sorted order and prints the nodes visited.

More Related Content

Similar to main.cpp#include TreeNode.h GIVEN void inorderTraversal(.pdf

Write the following using javaGiven a class ‘Node’ and ‘NodeList’,.pdf
Write the following using javaGiven a class ‘Node’ and ‘NodeList’,.pdfWrite the following using javaGiven a class ‘Node’ and ‘NodeList’,.pdf
Write the following using javaGiven a class ‘Node’ and ‘NodeList’,.pdf
fathimalinks
 
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
 
Data Structures in C++I am really new to C++, so links are really .pdf
Data Structures in C++I am really new to C++, so links are really .pdfData Structures in C++I am really new to C++, so links are really .pdf
Data Structures in C++I am really new to C++, so links are really .pdf
rohit219406
 
MAINCPP include ltiostreamgt include ltstringgt u.pdf
MAINCPP include ltiostreamgt include ltstringgt u.pdfMAINCPP include ltiostreamgt include ltstringgt u.pdf
MAINCPP include ltiostreamgt include ltstringgt u.pdf
adityastores21
 
Please write in C++ and should be able to compile and debug.Thank yo.pdf
Please write in C++ and should be able to compile and debug.Thank yo.pdfPlease write in C++ and should be able to compile and debug.Thank yo.pdf
Please write in C++ and should be able to compile and debug.Thank yo.pdf
ajaycosmeticslg
 
For this project, write a program that stores integers in a binary.docx
For this project, write a program that stores integers in a binary.docxFor this project, write a program that stores integers in a binary.docx
For this project, write a program that stores integers in a binary.docx
budbarber38650
 
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
 
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
 
Write a program that accepts an arithmetic expression of unsigned in.pdf
Write a program that accepts an arithmetic expression of unsigned in.pdfWrite a program that accepts an arithmetic expression of unsigned in.pdf
Write a program that accepts an arithmetic expression of unsigned in.pdf
JUSTSTYLISH3B2MOHALI
 
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdfAssignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
Footageetoffe16
 
create a binary search tree from an empty one by adding the key valu.pdf
create a binary search tree from an empty one by adding the key valu.pdfcreate a binary search tree from an empty one by adding the key valu.pdf
create a binary search tree from an empty one by adding the key valu.pdf
erremmfab
 
c++ Computational Complexity filling in the following three .pdf
c++ Computational Complexity filling in the  following three .pdfc++ Computational Complexity filling in the  following three .pdf
c++ Computational Complexity filling in the following three .pdf
amitbagga0808
 

Similar to main.cpp#include TreeNode.h GIVEN void inorderTraversal(.pdf (20)

Write the following using javaGiven a class ‘Node’ and ‘NodeList’,.pdf
Write the following using javaGiven a class ‘Node’ and ‘NodeList’,.pdfWrite the following using javaGiven a class ‘Node’ and ‘NodeList’,.pdf
Write the following using javaGiven a class ‘Node’ and ‘NodeList’,.pdf
 
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
 
Data Structures in C++I am really new to C++, so links are really .pdf
Data Structures in C++I am really new to C++, so links are really .pdfData Structures in C++I am really new to C++, so links are really .pdf
Data Structures in C++I am really new to C++, so links are really .pdf
 
MAINCPP include ltiostreamgt include ltstringgt u.pdf
MAINCPP include ltiostreamgt include ltstringgt u.pdfMAINCPP include ltiostreamgt include ltstringgt u.pdf
MAINCPP include ltiostreamgt include ltstringgt u.pdf
 
Please write in C++ and should be able to compile and debug.Thank yo.pdf
Please write in C++ and should be able to compile and debug.Thank yo.pdfPlease write in C++ and should be able to compile and debug.Thank yo.pdf
Please write in C++ and should be able to compile and debug.Thank yo.pdf
 
For this project, write a program that stores integers in a binary.docx
For this project, write a program that stores integers in a binary.docxFor this project, write a program that stores integers in a binary.docx
For this project, write a program that stores integers in a binary.docx
 
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
 
C++Write a method Node Nodereverse() which reverses a list..pdf
C++Write a method Node Nodereverse() which reverses a list..pdfC++Write a method Node Nodereverse() which reverses a list..pdf
C++Write a method Node Nodereverse() which reverses a list..pdf
 
Linked list
Linked listLinked list
Linked list
 
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
 
Write a program that accepts an arithmetic expression of unsigned in.pdf
Write a program that accepts an arithmetic expression of unsigned in.pdfWrite a program that accepts an arithmetic expression of unsigned in.pdf
Write a program that accepts an arithmetic expression of unsigned in.pdf
 
Assignment-6 (2).docx
Assignment-6 (2).docxAssignment-6 (2).docx
Assignment-6 (2).docx
 
Linked List.pptx
Linked List.pptxLinked List.pptx
Linked List.pptx
 
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdfAssignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
 
C program to insert a node in doubly linked list
C program to insert a node in doubly linked listC program to insert a node in doubly linked list
C program to insert a node in doubly linked list
 
COMP2710: Software Construction - Linked list exercises
COMP2710: Software Construction - Linked list exercisesCOMP2710: Software Construction - Linked list exercises
COMP2710: Software Construction - Linked list exercises
 
Binary Tree in C++ coding in the data structure
Binary Tree in C++ coding in the data structureBinary Tree in C++ coding in the data structure
Binary Tree in C++ coding in the data structure
 
Lab12 dsa bsee20075
Lab12 dsa bsee20075Lab12 dsa bsee20075
Lab12 dsa bsee20075
 
create a binary search tree from an empty one by adding the key valu.pdf
create a binary search tree from an empty one by adding the key valu.pdfcreate a binary search tree from an empty one by adding the key valu.pdf
create a binary search tree from an empty one by adding the key valu.pdf
 
c++ Computational Complexity filling in the following three .pdf
c++ Computational Complexity filling in the  following three .pdfc++ Computational Complexity filling in the  following three .pdf
c++ Computational Complexity filling in the following three .pdf
 

More from pratikradia365

M.B. is a 65-year-old male who is being admitted from the emergency .pdf
M.B. is a 65-year-old male who is being admitted from the emergency .pdfM.B. is a 65-year-old male who is being admitted from the emergency .pdf
M.B. is a 65-year-old male who is being admitted from the emergency .pdf
pratikradia365
 
L�neas de cruceros Carnival Aunque los viajes por mar han tenido.pdf
L�neas de cruceros Carnival Aunque los viajes por mar han tenido.pdfL�neas de cruceros Carnival Aunque los viajes por mar han tenido.pdf
L�neas de cruceros Carnival Aunque los viajes por mar han tenido.pdf
pratikradia365
 
Materia Comunicaci�n empresarialGui�n Esta es la historia de Ch.pdf
Materia Comunicaci�n empresarialGui�n Esta es la historia de Ch.pdfMateria Comunicaci�n empresarialGui�n Esta es la historia de Ch.pdf
Materia Comunicaci�n empresarialGui�n Esta es la historia de Ch.pdf
pratikradia365
 

More from pratikradia365 (20)

M.B. is a 65-year-old male who is being admitted from the emergency .pdf
M.B. is a 65-year-old male who is being admitted from the emergency .pdfM.B. is a 65-year-old male who is being admitted from the emergency .pdf
M.B. is a 65-year-old male who is being admitted from the emergency .pdf
 
L�neas de cruceros Carnival Aunque los viajes por mar han tenido.pdf
L�neas de cruceros Carnival Aunque los viajes por mar han tenido.pdfL�neas de cruceros Carnival Aunque los viajes por mar han tenido.pdf
L�neas de cruceros Carnival Aunque los viajes por mar han tenido.pdf
 
Los virus que infectan a los eucariotas tambi�n han evolucionado con.pdf
Los virus que infectan a los eucariotas tambi�n han evolucionado con.pdfLos virus que infectan a los eucariotas tambi�n han evolucionado con.pdf
Los virus que infectan a los eucariotas tambi�n han evolucionado con.pdf
 
Los t�cnicos m�dicos de emergencia (EMT, por sus siglas en ingl�s) n.pdf
Los t�cnicos m�dicos de emergencia (EMT, por sus siglas en ingl�s) n.pdfLos t�cnicos m�dicos de emergencia (EMT, por sus siglas en ingl�s) n.pdf
Los t�cnicos m�dicos de emergencia (EMT, por sus siglas en ingl�s) n.pdf
 
Los sistemas de control pueden hacer que las personas Pregunta 13 .pdf
Los sistemas de control pueden hacer que las personas Pregunta 13 .pdfLos sistemas de control pueden hacer que las personas Pregunta 13 .pdf
Los sistemas de control pueden hacer que las personas Pregunta 13 .pdf
 
Los tres tipos principales de pron�sticos utilizados por las organiz.pdf
Los tres tipos principales de pron�sticos utilizados por las organiz.pdfLos tres tipos principales de pron�sticos utilizados por las organiz.pdf
Los tres tipos principales de pron�sticos utilizados por las organiz.pdf
 
Los trabajadores 1,..., n est�n actualmente inactivos. Supongamos qu.pdf
Los trabajadores 1,..., n est�n actualmente inactivos. Supongamos qu.pdfLos trabajadores 1,..., n est�n actualmente inactivos. Supongamos qu.pdf
Los trabajadores 1,..., n est�n actualmente inactivos. Supongamos qu.pdf
 
Los tipos de sangre humana se heredan en un patr�n co-dominante. Hay.pdf
Los tipos de sangre humana se heredan en un patr�n co-dominante. Hay.pdfLos tipos de sangre humana se heredan en un patr�n co-dominante. Hay.pdf
Los tipos de sangre humana se heredan en un patr�n co-dominante. Hay.pdf
 
Los valores m�s grandes de tienen la desventaja de aumentar la proba.pdf
Los valores m�s grandes de tienen la desventaja de aumentar la proba.pdfLos valores m�s grandes de tienen la desventaja de aumentar la proba.pdf
Los valores m�s grandes de tienen la desventaja de aumentar la proba.pdf
 
Los siguientes son motivos razonables para las fusiones I) evitar.pdf
Los siguientes son motivos razonables para las fusiones I) evitar.pdfLos siguientes son motivos razonables para las fusiones I) evitar.pdf
Los siguientes son motivos razonables para las fusiones I) evitar.pdf
 
Los proveedores de atenci�n m�dica son responsables de documentar y .pdf
Los proveedores de atenci�n m�dica son responsables de documentar y .pdfLos proveedores de atenci�n m�dica son responsables de documentar y .pdf
Los proveedores de atenci�n m�dica son responsables de documentar y .pdf
 
mauriland is a fictitious country with only two politically active g.pdf
mauriland is a fictitious country with only two politically active g.pdfmauriland is a fictitious country with only two politically active g.pdf
mauriland is a fictitious country with only two politically active g.pdf
 
Los puntos principales, subpuntos y subsubpuntos deben escribirse en.pdf
Los puntos principales, subpuntos y subsubpuntos deben escribirse en.pdfLos puntos principales, subpuntos y subsubpuntos deben escribirse en.pdf
Los puntos principales, subpuntos y subsubpuntos deben escribirse en.pdf
 
Mathew siempre llega tarde a la oficina. Al gerente de Mathew no le .pdf
Mathew siempre llega tarde a la oficina. Al gerente de Mathew no le .pdfMathew siempre llega tarde a la oficina. Al gerente de Mathew no le .pdf
Mathew siempre llega tarde a la oficina. Al gerente de Mathew no le .pdf
 
Los riesgos que pueden resultar en que un sistema o proceso no fun.pdf
Los riesgos que pueden resultar en que un sistema o proceso no fun.pdfLos riesgos que pueden resultar en que un sistema o proceso no fun.pdf
Los riesgos que pueden resultar en que un sistema o proceso no fun.pdf
 
Match up the following The chance of a type 2 error is reduced.pdf
Match up the following The chance of a type 2 error is reduced.pdfMatch up the following The chance of a type 2 error is reduced.pdf
Match up the following The chance of a type 2 error is reduced.pdf
 
Match the Late Paleozoic time period with the appropriate life. You.pdf
Match the Late Paleozoic time period with the appropriate life.  You.pdfMatch the Late Paleozoic time period with the appropriate life.  You.pdf
Match the Late Paleozoic time period with the appropriate life. You.pdf
 
Match the following proteins with the best description of their func.pdf
Match the following proteins with the best description of their func.pdfMatch the following proteins with the best description of their func.pdf
Match the following proteins with the best description of their func.pdf
 
Materia Comunicaci�n empresarialGui�n Esta es la historia de Ch.pdf
Materia Comunicaci�n empresarialGui�n Esta es la historia de Ch.pdfMateria Comunicaci�n empresarialGui�n Esta es la historia de Ch.pdf
Materia Comunicaci�n empresarialGui�n Esta es la historia de Ch.pdf
 
Match the STRIDE threat with its description. Match the STRIDE threa.pdf
Match the STRIDE threat with its description. Match the STRIDE threa.pdfMatch the STRIDE threat with its description. Match the STRIDE threa.pdf
Match the STRIDE threat with its description. Match the STRIDE threa.pdf
 

Recently uploaded

Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
AnaAcapella
 
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lessonQUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
httgc7rh9c
 

Recently uploaded (20)

80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Economic Importance Of Fungi In Food Additives
Economic Importance Of Fungi In Food AdditivesEconomic Importance Of Fungi In Food Additives
Economic Importance Of Fungi In Food Additives
 
Introduction to TechSoup’s Digital Marketing Services and Use Cases
Introduction to TechSoup’s Digital Marketing  Services and Use CasesIntroduction to TechSoup’s Digital Marketing  Services and Use Cases
Introduction to TechSoup’s Digital Marketing Services and Use Cases
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
 
Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111
 
dusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learningdusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learning
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lessonQUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdfUGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
 
VAMOS CUIDAR DO NOSSO PLANETA! .
VAMOS CUIDAR DO NOSSO PLANETA!                    .VAMOS CUIDAR DO NOSSO PLANETA!                    .
VAMOS CUIDAR DO NOSSO PLANETA! .
 
Simple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfSimple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdf
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 

main.cpp#include TreeNode.h GIVEN void inorderTraversal(.pdf

  • 1. main.cpp #include "TreeNode.h" //GIVEN void inorderTraversal(TreeNode * root); //TODO TreeNode * search(TreeNode * node,int data); //GIVEN void insert(TreeNode * node,int data); //GIVEN bool isNull(TreeNode * node){ return node==nullptr; } int main() { // create the root, gets set to null TreeNode * root; // create the roor and set the data of root to 5 root= new TreeNode(5); //create two additional nodes with data values 10 and 3 // these will go to the right and left of root respectively TreeNode * ten= new TreeNode(10); TreeNode * three= new TreeNode(3); //connect ten to the right of root (which has data 5) root->setRight(ten); //connect three to the left of root (which has data 5) root->setLeft(three); // note this can also be done as //root.setRight(new TreeNode(10)); //root.setLeft(new TreeNode(3);) // add two more nodes //the first has data value 7. So to keep the tree in insorted order, it should get attached as the left node of ten // the second has data value 4. So to keep the tree in insorted order, it should get attached as the
  • 2. right node of three ten->addLeft(7); three->addRight(4); std::cout<<"**************************************n"; std::cout<<"Printing the Inorder Traversaln"; inorderTraversal(root); std::cout<<"**************************************n"; std::cout<<"Searching for Node n"; TreeNode* result = search(root,4); if (result!=nullptr){ std::cout<<"Found "<getData()<<"n"; } else std::cout<<"Not Found "<<4<<"n"; result = search(root,1); if (result!=nullptr){ std::cout<<"Found "<getData()<<"n"; } else std::cout<<"Not Found "<<1<<"n"; std::cout<<"**************************************n"; std::cout<<"Inserting 6n"; insert(root,6); std::cout<<"**************************************n"; std::cout<<"Printing the Inorder Traversaln"; inorderTraversal(root); } // uses recursion void inorderTraversal(TreeNode * node){ // exit case
  • 3. if (isNull(node)) return; if (node->isLeaf()){ std::cout<<"Printing Leaf Node "<getData()<<"n"; return;} // reached a node with no left, so print the node and travel right if (!isNull(node->getLeft())) // if there is a left path, then travel further on that inorderTraversal(node->getLeft()); std::cout<<"Printing Node "<getData()<<"n"; // save and travel the right path of the current node being processed inorderTraversal(node->getRight()); } // uses recursion //TODO TreeNode * search(TreeNode * node, int data){ // if the node is null return the null ptr //if this nodes data equals the search date return found // if not, if the left tree exists and search data less than //this nodes data return the result of recursive all to search with left pointer // if no left tree, but right tree exists and search data greater than //this nodes data return the result of recursive all to search with right pointer // if both above conditions not true return null ptr } //uses recursion void insert(TreeNode * node,int data){ if (node->getData()==data) return; else if(datagetData()){ if (!isNull(node->getLeft())) // std::cout<<"Going Left from "<getData()<<"n"; return insert(node->getLeft(),data); else node->setLeft(new TreeNode(data)); }
  • 4. else if (data>node->getData()){ if (!isNull(node->getRight())) return insert(node->getRight(),data); else node->setRight(new TreeNode(data)); } } TreeNode.cpp #include "TreeNode.h" TreeNode::TreeNode(){ data=0; left=nullptr; right=nullptr; } TreeNode::TreeNode(int data){ this->data=data; this->left=nullptr; this->right=nullptr; } TreeNode::TreeNode(int data,TreeNode * left, TreeNode * right){ this->data=data; this->left=left; this->right=right; } void TreeNode::setData(int data){ this->data=data; } int TreeNode::getData(){ return data; } //TODO TreeNode * TreeNode::getLeft(){ // }
  • 5. TreeNode * TreeNode::getRight(){ return right; } // does not create any new node. Just sets the right pointer void TreeNode::setRight(TreeNode *newRight){ right=newRight; } // does not create any new node. Just sets the left pointer //TODO void TreeNode::setLeft(TreeNode *newLeft){ // } bool TreeNode::isLeaf(){ return (left==nullptr&&right==nullptr); } //creates a new node with the data value and sets the rightpointer to it void TreeNode::addRight(int data){ right= new TreeNode(data,nullptr,nullptr); } //creates a new node with the data value and sets the left pointer to it //TODO void TreeNode::addLeft(int data){ // } TreeNode.h #include #include #include class TreeNode{ private: int data; private: TreeNode * left; private: TreeNode * right; public:
  • 6. TreeNode(); TreeNode(int data); TreeNode(int data, TreeNode * left, TreeNode * right); void setData(int data); int getData(); bool isLeaf(); TreeNode * getLeft(); TreeNode * getRight(); void setRight(TreeNode *newRight); void setLeft(TreeNode *newLeft); void addRight(int data); void addLeft(int data); }; Make sure that the completed code would display the below output: ************************************** Printing the Inorder Traversal Printing Node 3 Printing Leaf Node 4 Printing Node 5 Printing Leaf Node 7 Printing Node 10 ************************************** Searching for Node Found 4 Not Found 1 ************************************** Inserting 6 ************************************** Printing the Inorder Traversal Printing Node 3 Printing Leaf Node 4 Printing Node 5 Printing Leaf Node 6 Printing Node 7
  • 7. Printing Node 10 Description You are given a template that contains the TreeNode class header and partially implemented TreeNode.cpp file. A driver is also included. This driver constructs TreeNode objects and connects their pointers, manually creating a sorted binary tree. Methods to insert nodes while keeping the tree sorted is implemented as also to traverse the tree "inorder". A search method that traverses the tree to search for a given data value needs to be written. Recursion is used in all these methods. The output file is also given to you TreeNode private: int data; private: TreeNode * left; private: TreeNode * right; public: TreeNode(); //default constructor: sets data to 0, pointers to nullptr TreeNode(int data); //custom constructor: sets this data to data, pointers to nullptr TreeNode(int data, TreeNode * left, TreeNode * right); custom constructor, sets data and pointers void setData(int data); // sets data int getData(); // returns data bool isLeaf(); // returns true if both pointers are null. TreeNode * getLeft(); // returns left Pointer TreeNode * getRight(); //returns left Pointer void setRight(TreeNode *newRight); sets right Pointer void setLeft(TreeNode *newLeft); sets left Pointer void addRight(int data); adds a new TreeNode with this data to the right of current TreeNode void addLeft(int data); adds a new TreeNode with this data to the left of current TreeNode }; Most of these methods have been implemented. Please implement the "right" methods by examining the "left" methods TreeNode * getLeft(); // returns left Pointer void setLeft(TreeNode *newLeft); sets left Pointer void addLeft(int data); adds a new TreeNode with this data to the left of current TreeNode # The driver is given is given to you that does the following 1. Creates a root TreeNode with data value 5 2. Create two additional nodes with data values 10 and 3 3. Set these to the right and left of root respectively 4. Add two more nodes- the first has data value 7. So to keep the tree in insorted order, it should get attached as the left node of ten 5. Add the second node with data value 4 . So to keep the tree in insorted order, it should get attached as the right node of three 6. Call the inorderTraversal methods that traverses the tree starting from the root, in sorted order and prints the nodes visited. 7. Search for an existing node with data value 4 . 8. Search for a non existing node with data value 1. 9. Insert a new node with data value 6 . 10. Call the inorderTraversal methods that traverses the tree starting from the root, in sorted order and prints the nodes visited.