SlideShare a Scribd company logo
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

PDF
Please write the C++ code that would display the exact same output a.pdf
PDF
Given a newly created Binary Search Tree with the following numerica.pdf
PDF
include ltiostreamgt include ltfstreamgt in.pdf
PPTX
Binary Search Tree.pptxA binary search i
PDF
Program to insert in a sorted list #includestdio.h#include.pdf
PDF
1#include stdio.h#include stdlib.h#include assert.h .pdf
PDF
This assignment and the next (#5) involve design and development of a.pdf
PPTX
DS group binary tree all information M.pptx
Please write the C++ code that would display the exact same output a.pdf
Given a newly created Binary Search Tree with the following numerica.pdf
include ltiostreamgt include ltfstreamgt in.pdf
Binary Search Tree.pptxA binary search i
Program to insert in a sorted list #includestdio.h#include.pdf
1#include stdio.h#include stdlib.h#include assert.h .pdf
This assignment and the next (#5) involve design and development of a.pdf
DS group binary tree all information M.pptx

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

PDF
Tree Traversals A tree traversal is the process of visiting.pdf
PDF
A)B) C++ program to create a Complete Binary tree from its Lin.pdf
PDF
Write the following using javaGiven a class ‘Node’ and ‘NodeList’,.pdf
DOCX
Once you have all the structures working as intended- it is time to co.docx
PDF
Data Structures in C++I am really new to C++, so links are really .pdf
PDF
MAINCPP include ltiostreamgt include ltstringgt u.pdf
PDF
Please write in C++ and should be able to compile and debug.Thank yo.pdf
DOCX
For this project, write a program that stores integers in a binary.docx
PDF
THE CODE HAS A SEGMENTATION FAULT BUT I CANNOT FIND OUT WHERE. NEED .pdf
PDF
C++Write a method Node Nodereverse() which reverses a list..pdf
PDF
Linked list
PDF
Use C++ Write a function to merge two doubly linked lists. The input.pdf
PDF
Write a program that accepts an arithmetic expression of unsigned in.pdf
DOCX
Assignment-6 (2).docx
PPTX
Linked List.pptx
PDF
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
DOC
C program to insert a node in doubly linked list
PPT
COMP2710: Software Construction - Linked list exercises
DOCX
Binary Tree in C++ coding in the data structure
PDF
Lab12 dsa bsee20075
Tree Traversals A tree traversal is the process of visiting.pdf
A)B) C++ program to create a Complete Binary tree from its Lin.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
Data Structures in C++I am really new to C++, so links are really .pdf
MAINCPP include ltiostreamgt include ltstringgt u.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
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
Linked list
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
Assignment-6 (2).docx
Linked List.pptx
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
C program to insert a node in doubly linked list
COMP2710: Software Construction - Linked list exercises
Binary Tree in C++ coding in the data structure
Lab12 dsa bsee20075
Ad

More from pratikradia365 (20)

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

Recently uploaded (20)

PDF
Basic Mud Logging Guide for educational purpose
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
Pre independence Education in Inndia.pdf
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
Classroom Observation Tools for Teachers
PPTX
master seminar digital applications in india
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
Sports Quiz easy sports quiz sports quiz
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
TR - Agricultural Crops Production NC III.pdf
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
GDM (1) (1).pptx small presentation for students
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
01-Introduction-to-Information-Management.pdf
Basic Mud Logging Guide for educational purpose
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Pre independence Education in Inndia.pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Classroom Observation Tools for Teachers
master seminar digital applications in india
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
O7-L3 Supply Chain Operations - ICLT Program
PPH.pptx obstetrics and gynecology in nursing
VCE English Exam - Section C Student Revision Booklet
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Sports Quiz easy sports quiz sports quiz
Abdominal Access Techniques with Prof. Dr. R K Mishra
TR - Agricultural Crops Production NC III.pdf
Renaissance Architecture: A Journey from Faith to Humanism
2.FourierTransform-ShortQuestionswithAnswers.pdf
Supply Chain Operations Speaking Notes -ICLT Program
GDM (1) (1).pptx small presentation for students
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
01-Introduction-to-Information-Management.pdf

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.