SlideShare a Scribd company logo
1 of 13
Download to read offline
1. Add a breadth-first (level-order) traversal function to the binary tree code.
2. Add a function to find the height of a tree.
3. Re-implement one of the depth-first traversal methods using a stack instead of recursion.
4. Add a link to each nodes parent node.
#include
#include
#include
using namespace std;
template < typename T >
class TreeNode
{
public:
T element; //
TreeNode < T > * left; //
TreeNode < T > * right; //
TreeNode * next;
TreeNode() //
{
left = NULL;
next = NULL;
}
TreeNode(T element) // Constructor
{
this->element = element;
left = NULL;
right = NULL;
}
};
template < typename T >
class BinaryTree
{
public:
BinaryTree();
BinaryTree(T elements[], int arraySize);
bool insert(T element);
void inorder();
void preorder();
void postorder();
int getSize();
bool search(T element);
void breadthFirstTraversal();
int depth();
private:
TreeNode < T > * root;
int size;
void inorder(TreeNode < T > * root);
void postorder(TreeNode < T > * root);
void preorder(TreeNode < T > * root);
bool search(T element, TreeNode < T > * root);
int depth(TreeNode * root);
};
template < typename T >
BinaryTree < T >::BinaryTree()
{
root = NULL;
size = 0;
}
template < typename T >
BinaryTree < T >::BinaryTree(T elements[], int arraySize)
{
root = NULL;
size = 0;
for (int i = 0; i < arraySize; i++)
{
insert(elements[i]);
}
}
template < typename T >
bool BinaryTree < T >::insert(T element)
{
if (root == NULL)
root = new TreeNode < T > (element); // Create a new root
else
{
// Locate the parent node
TreeNode < T > * parent = NULL;
TreeNode < T > * current = root;
while (current != NULL)
if (element < current->element)
{
parent = current;
current = current->left;
}
else if (element > current->element)
{
parent = current;
current = current->right;
}
else
return false; // Duplicate node not inserted
// Create the new node and attach it to the parent node
if (element < parent->element)
parent->left = new TreeNode < T > (element);
else
parent->right = new TreeNode < T > (element);
}
size++;
return true; // Element inserted
}
/* Inorder traversal */
template < typename T >
void BinaryTree < T >::inorder()
{
inorder(root);
}
/* Inorder traversal from a subtree */
template < typename T >
void BinaryTree < T >::inorder(TreeNode < T > * root)
{
if (root == NULL) return;
inorder(root->left);
cout << root->element << " ";
inorder(root->right);
}
/* Postorder traversal */
template < typename T >
void BinaryTree < T >::postorder()
{
postorder(root);
}
/** Inorder traversal from a subtree */
template < typename T >
void BinaryTree < T >::postorder(TreeNode < T > * root)
{
if (root == NULL) return;
postorder(root->left);
postorder(root->right);
cout << root->element << " ";
}
/* */
template < typename T >
void BinaryTree < T >::preorder()
{
preorder(root);
}
/* */
template < typename T >
void BinaryTree < T >::preorder(TreeNode < T > * root)
{
if (root == NULL) return;
cout << root->element << " ";
preorder(root->left);
preorder(root->right);
}
/**/
template < typename T >
int BinaryTree < T >::getSize()
{
return size;
}
template < typename T >
bool BinaryTree < T >::search(T element)
{
return search(element, root);
}
template < typename T >
bool BinaryTree < T >::search(T element, TreeNode < T > * root)
{
if (root == NULL)
return false;
else if (root->element == element)
return true;
else if (root->element > element)
return search(element, root->right);
else
return search(element, root->left);
}
int main()
{
BinaryTree < string > tree1;
tree1.insert("George");
tree1.insert("Michael");
tree1.insert("Tom");
tree1.insert("Adam");
tree1.insert("Jones");
tree1.insert("Peter");
tree1.insert("Daniel");
cout << "Inorder (sorted): ";
tree1.inorder();
cout << " Postorder: ";
tree1.postorder();
cout << " Preorder: ";
tree1.preorder();
cout << " The number of nodes is " << tree1.getSize();
int numbers[] =
{
2, 4, 3, 1, 8, 5, 6, 7
};
BinaryTree < int > tree2(numbers, 8);
cout << " Inorder (sorted): ";
tree2.inorder();
cout << " search 2 " << tree2.search(2) << endl;
cout << " search 99 " << tree2.search(99) << endl;
cout << " search 8 " << tree2.search(8) << endl;
return 0;
}
Solution
#include
#include
#include
using namespace std;
template < typename T >
class TreeNode
{
public:
T element; //
TreeNode < T > * left; //
TreeNode < T > * right; //
TreeNode * next;
TreeNode() //
{
left = NULL;
next = NULL;
}
TreeNode(T element) // Constructor
{
this->element = element;
left = NULL;
right = NULL;
}
};
template < typename T >
class BinaryTree
{
public:
BinaryTree();
BinaryTree(T elements[], int arraySize);
bool insert(T element);
void inorder();
void preorder();
void postorder();
int getSize();
bool search(T element);
void breadthFirstTraversal();
int depth();
void BFS();
private:
TreeNode < T > * root;
int size;
void inorder(TreeNode < T > * root);
void postorder(TreeNode < T > * root);
void preorder(TreeNode < T > * root);
bool search(T element, TreeNode < T > * root);
int depth(TreeNode * root);
void printLevelOrder(TreeNode < T > * root);
void printGivenLevel(TreeNode < T > * root, int level);
};
template < typename T >
int BinaryTree < T >::depth()
{
depth(root);
}
template < typename T >
void BinaryTree < T >::BFS()
{
printLevelOrder(root);
}
template < typename T >
void BinaryTree < T >::printLevelOrder(TreeNode < T > * root)
{
int h = depth(root);
int i;
for (i=1; i<=h; i++)
printGivenLevel(root, i);
}
/* Print nodes at a given level */
template < typename T >
void BinaryTree < T >::printGivenLevel(TreeNode < T > * root, int level)
{
if (root == NULL)
return;
if (level == 1)
cout<<" "<element;
else if (level > 1)
{
printGivenLevel(root->left, level-1);
printGivenLevel(root->right, level-1);
}
}
template < typename T >
int BinaryTree < T >::depth(TreeNode < T > * element)
{
if (element==NULL)
return 0;
else
{
int lDepth = depth(element->left);
int rDepth = depth(element->right);
// use the larger one
if (lDepth > rDepth)
return(lDepth+1);
else return(rDepth+1);
}
}
template < typename T >
BinaryTree < T >::BinaryTree()
{
root = NULL;
size = 0;
}
template < typename T >
BinaryTree < T >::BinaryTree(T elements[], int arraySize)
{
root = NULL;
size = 0;
for (int i = 0; i < arraySize; i++)
{
insert(elements[i]);
}
}
template < typename T >
bool BinaryTree < T >::insert(T element)
{
if (root == NULL)
root = new TreeNode < T > (element); // Create a new root
else
{
// Locate the parent node
TreeNode < T > * parent = NULL;
TreeNode < T > * current = root;
while (current != NULL)
if (element < current->element)
{
parent = current;
current = current->left;
}
else if (element > current->element)
{
parent = current;
current = current->right;
}
else
return false; // Duplicate node not inserted
// Create the new node and attach it to the parent node
if (element < parent->element)
parent->left = new TreeNode < T > (element);
else
parent->right = new TreeNode < T > (element);
}
size++;
return true; // Element inserted
}
/* Inorder traversal */
template < typename T >
void BinaryTree < T >::inorder()
{
inorder(root);
}
/* Inorder traversal from a subtree */
template < typename T >
void BinaryTree < T >::inorder(TreeNode < T > * root)
{
if (root == NULL) return;
inorder(root->left);
cout << root->element << " ";
inorder(root->right);
}
/* Postorder traversal */
template < typename T >
void BinaryTree < T >::postorder()
{
postorder(root);
}
/** Inorder traversal from a subtree */
template < typename T >
void BinaryTree < T >::postorder(TreeNode < T > * root)
{
if (root == NULL) return;
postorder(root->left);
postorder(root->right);
cout << root->element << " ";
}
/* */
template < typename T >
void BinaryTree < T >::preorder()
{
preorder(root);
}
/* */
template < typename T >
void BinaryTree < T >::preorder(TreeNode < T > * root)
{
if (root == NULL) return;
cout << root->element << " ";
preorder(root->left);
preorder(root->right);
}
/**/
template < typename T >
int BinaryTree < T >::getSize()
{
return size;
}
template < typename T >
bool BinaryTree < T >::search(T element)
{
return search(element, root);
}
template < typename T >
bool BinaryTree < T >::search(T element, TreeNode < T > * root)
{
if (root == NULL)
return false;
else if (root->element == element)
return true;
else if (root->element > element)
return search(element, root->right);
else
return search(element, root->left);
}
int main()
{
BinaryTree < string > tree1;
tree1.insert("George");
tree1.insert("Michael");
tree1.insert("Tom");
tree1.insert("Adam");
tree1.insert("Jones");
tree1.insert("Peter");
tree1.insert("Daniel");
cout << "Inorder (sorted): ";
tree1.inorder();
cout << " Postorder: ";
tree1.postorder();
cout << " Preorder: ";
tree1.preorder();
cout << " The number of nodes is " << tree1.getSize();
int numbers[] =
{
2, 4, 3, 1, 8, 5, 6, 7
};
BinaryTree < int > tree2(numbers, 8);
cout << " Inorder (sorted): ";
tree2.inorder();
cout << " search 2 " << tree2.search(2) << endl;
cout << " search 99 " << tree2.search(99) << endl;
cout << " search 8 " << tree2.search(8) << endl;
cout<<"Height is "<

More Related Content

Similar to 1. Add a breadth-first (level-order) traversal function to the binar.pdf

program on string in java Lab file 2 (3-year)
program on string in java Lab file 2 (3-year)program on string in java Lab file 2 (3-year)
program on string in java Lab file 2 (3-year)Ankit Gupta
 
Required to augment the authors Binary Search Tree (BST) code to .docx
Required to augment the authors Binary Search Tree (BST) code to .docxRequired to augment the authors Binary Search Tree (BST) code to .docx
Required to augment the authors Binary Search Tree (BST) code to .docxdebishakespeare
 
My C proggram is having trouble in the switch in main. Also the a co.pdf
My C proggram is having trouble in the switch in main. Also the a co.pdfMy C proggram is having trouble in the switch in main. Also the a co.pdf
My C proggram is having trouble in the switch in main. Also the a co.pdfmeerobertsonheyde608
 
Please read the comment ins codeExpressionTree.java-------------.pdf
Please read the comment ins codeExpressionTree.java-------------.pdfPlease read the comment ins codeExpressionTree.java-------------.pdf
Please read the comment ins codeExpressionTree.java-------------.pdfshanki7
 
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.pdfJUSTSTYLISH3B2MOHALI
 
AnswerThe new program with the required constructor and with a te.pdf
AnswerThe new program with the required constructor and with a te.pdfAnswerThe new program with the required constructor and with a te.pdf
AnswerThe new program with the required constructor and with a te.pdfnipuns1983
 
Doublylinklist
DoublylinklistDoublylinklist
Doublylinklistritu1806
 
BinarySearchTrees.ppt
BinarySearchTrees.pptBinarySearchTrees.ppt
BinarySearchTrees.pptItsStranger1
 
BinarySearchTrees (1).ppt
BinarySearchTrees (1).pptBinarySearchTrees (1).ppt
BinarySearchTrees (1).pptplagcheck
 
BinarySearchTrees.ppt
BinarySearchTrees.pptBinarySearchTrees.ppt
BinarySearchTrees.pptplagcheck
 
data structure very BinarySearchTrees.ppt
data structure very BinarySearchTrees.pptdata structure very BinarySearchTrees.ppt
data structure very BinarySearchTrees.pptDharmannaRathod1
 
Given the following codepackage data1;import java.util.;p.pdf
Given the following codepackage data1;import java.util.;p.pdfGiven the following codepackage data1;import java.util.;p.pdf
Given the following codepackage data1;import java.util.;p.pdfillyasraja7
 
Please help write BinaryTree-java Thank you! Create a class BinaryTr.pdf
Please help write BinaryTree-java Thank you!   Create a class BinaryTr.pdfPlease help write BinaryTree-java Thank you!   Create a class BinaryTr.pdf
Please help write BinaryTree-java Thank you! Create a class BinaryTr.pdfinfo750646
 
Here is the code given in the instructionsclass AVL {.pdf
Here is the code given in the instructionsclass AVL {.pdfHere is the code given in the instructionsclass AVL {.pdf
Here is the code given in the instructionsclass AVL {.pdfmanjan6
 
Lab Week 2 Game Programming.docx
Lab Week 2 Game Programming.docxLab Week 2 Game Programming.docx
Lab Week 2 Game Programming.docxteyaj1
 
GIVEN CODE template -typename T- class DList { private- struct Node {.docx
GIVEN CODE template -typename T- class DList { private- struct Node {.docxGIVEN CODE template -typename T- class DList { private- struct Node {.docx
GIVEN CODE template -typename T- class DList { private- struct Node {.docxLeonardN9WWelchw
 

Similar to 1. Add a breadth-first (level-order) traversal function to the binar.pdf (20)

program on string in java Lab file 2 (3-year)
program on string in java Lab file 2 (3-year)program on string in java Lab file 2 (3-year)
program on string in java Lab file 2 (3-year)
 
Required to augment the authors Binary Search Tree (BST) code to .docx
Required to augment the authors Binary Search Tree (BST) code to .docxRequired to augment the authors Binary Search Tree (BST) code to .docx
Required to augment the authors Binary Search Tree (BST) code to .docx
 
My C proggram is having trouble in the switch in main. Also the a co.pdf
My C proggram is having trouble in the switch in main. Also the a co.pdfMy C proggram is having trouble in the switch in main. Also the a co.pdf
My C proggram is having trouble in the switch in main. Also the a co.pdf
 
Please read the comment ins codeExpressionTree.java-------------.pdf
Please read the comment ins codeExpressionTree.java-------------.pdfPlease read the comment ins codeExpressionTree.java-------------.pdf
Please read the comment ins codeExpressionTree.java-------------.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
 
AnswerThe new program with the required constructor and with a te.pdf
AnswerThe new program with the required constructor and with a te.pdfAnswerThe new program with the required constructor and with a te.pdf
AnswerThe new program with the required constructor and with a te.pdf
 
Doublylinklist
DoublylinklistDoublylinklist
Doublylinklist
 
Linked lists
Linked listsLinked lists
Linked lists
 
BinarySearchTrees.ppt
BinarySearchTrees.pptBinarySearchTrees.ppt
BinarySearchTrees.ppt
 
BinarySearchTrees.ppt
BinarySearchTrees.pptBinarySearchTrees.ppt
BinarySearchTrees.ppt
 
BinarySearchTrees (1).ppt
BinarySearchTrees (1).pptBinarySearchTrees (1).ppt
BinarySearchTrees (1).ppt
 
Binary searchtrees
Binary searchtreesBinary searchtrees
Binary searchtrees
 
BinarySearchTrees.ppt
BinarySearchTrees.pptBinarySearchTrees.ppt
BinarySearchTrees.ppt
 
data structure very BinarySearchTrees.ppt
data structure very BinarySearchTrees.pptdata structure very BinarySearchTrees.ppt
data structure very BinarySearchTrees.ppt
 
Given the following codepackage data1;import java.util.;p.pdf
Given the following codepackage data1;import java.util.;p.pdfGiven the following codepackage data1;import java.util.;p.pdf
Given the following codepackage data1;import java.util.;p.pdf
 
Linked lists
Linked listsLinked lists
Linked lists
 
Please help write BinaryTree-java Thank you! Create a class BinaryTr.pdf
Please help write BinaryTree-java Thank you!   Create a class BinaryTr.pdfPlease help write BinaryTree-java Thank you!   Create a class BinaryTr.pdf
Please help write BinaryTree-java Thank you! Create a class BinaryTr.pdf
 
Here is the code given in the instructionsclass AVL {.pdf
Here is the code given in the instructionsclass AVL {.pdfHere is the code given in the instructionsclass AVL {.pdf
Here is the code given in the instructionsclass AVL {.pdf
 
Lab Week 2 Game Programming.docx
Lab Week 2 Game Programming.docxLab Week 2 Game Programming.docx
Lab Week 2 Game Programming.docx
 
GIVEN CODE template -typename T- class DList { private- struct Node {.docx
GIVEN CODE template -typename T- class DList { private- struct Node {.docxGIVEN CODE template -typename T- class DList { private- struct Node {.docx
GIVEN CODE template -typename T- class DList { private- struct Node {.docx
 

More from arjuncp10

I l Show that if X has the discrete topology, then its only conn.pdf
I l Show that if X has the discrete topology, then its only conn.pdfI l Show that if X has the discrete topology, then its only conn.pdf
I l Show that if X has the discrete topology, then its only conn.pdfarjuncp10
 
In 2006 the CEO of Bear Sterns, James Caynes, received a compensatio.pdf
In 2006 the CEO of Bear Sterns, James Caynes, received a compensatio.pdfIn 2006 the CEO of Bear Sterns, James Caynes, received a compensatio.pdf
In 2006 the CEO of Bear Sterns, James Caynes, received a compensatio.pdfarjuncp10
 
How would a CFE devise a plan to prevent subsequent employee fraud.pdf
How would a CFE devise a plan to prevent subsequent employee fraud.pdfHow would a CFE devise a plan to prevent subsequent employee fraud.pdf
How would a CFE devise a plan to prevent subsequent employee fraud.pdfarjuncp10
 
Hilary rode her horse for 8 miles until it was hurt.Then she walked .pdf
Hilary rode her horse for 8 miles until it was hurt.Then she walked .pdfHilary rode her horse for 8 miles until it was hurt.Then she walked .pdf
Hilary rode her horse for 8 miles until it was hurt.Then she walked .pdfarjuncp10
 
fully comments for my program, thank you will thumb up#include io.pdf
fully comments for my program, thank you will thumb up#include io.pdffully comments for my program, thank you will thumb up#include io.pdf
fully comments for my program, thank you will thumb up#include io.pdfarjuncp10
 
Find the admittance Yab in the circuit seen in the figure. Take that.pdf
Find the admittance Yab in the circuit seen in the figure. Take that.pdfFind the admittance Yab in the circuit seen in the figure. Take that.pdf
Find the admittance Yab in the circuit seen in the figure. Take that.pdfarjuncp10
 
Diversity Paper Each student will complete a diversity research assig.pdf
Diversity Paper Each student will complete a diversity research assig.pdfDiversity Paper Each student will complete a diversity research assig.pdf
Diversity Paper Each student will complete a diversity research assig.pdfarjuncp10
 
Detailed solutions please 1. Let R and S be commutative rings and le.pdf
Detailed solutions please 1. Let R and S be commutative rings and le.pdfDetailed solutions please 1. Let R and S be commutative rings and le.pdf
Detailed solutions please 1. Let R and S be commutative rings and le.pdfarjuncp10
 
Describe the mechanisms of asexual reproduction inProkaryotesPr.pdf
Describe the mechanisms of asexual reproduction inProkaryotesPr.pdfDescribe the mechanisms of asexual reproduction inProkaryotesPr.pdf
Describe the mechanisms of asexual reproduction inProkaryotesPr.pdfarjuncp10
 
Define intermediate phenotype and then imagine some intermediate phe.pdf
Define intermediate phenotype and then imagine some intermediate phe.pdfDefine intermediate phenotype and then imagine some intermediate phe.pdf
Define intermediate phenotype and then imagine some intermediate phe.pdfarjuncp10
 
Consider a population of lizards living on the coast of Africa. A sto.pdf
Consider a population of lizards living on the coast of Africa. A sto.pdfConsider a population of lizards living on the coast of Africa. A sto.pdf
Consider a population of lizards living on the coast of Africa. A sto.pdfarjuncp10
 
Can “discovery science” (for example, the discovery of a new species.pdf
Can “discovery science” (for example, the discovery of a new species.pdfCan “discovery science” (for example, the discovery of a new species.pdf
Can “discovery science” (for example, the discovery of a new species.pdfarjuncp10
 
C++Write a function void headEnqueue(Queue q, int key) which enqu.pdf
C++Write a function void headEnqueue(Queue q, int key) which enqu.pdfC++Write a function void headEnqueue(Queue q, int key) which enqu.pdf
C++Write a function void headEnqueue(Queue q, int key) which enqu.pdfarjuncp10
 
All of the following are features or functions of nanobodies except _.pdf
All of the following are features or functions of nanobodies except _.pdfAll of the following are features or functions of nanobodies except _.pdf
All of the following are features or functions of nanobodies except _.pdfarjuncp10
 
A girl running at a constant speed of 1.4ms in a straight line thro.pdf
A girl running at a constant speed of 1.4ms in a straight line thro.pdfA girl running at a constant speed of 1.4ms in a straight line thro.pdf
A girl running at a constant speed of 1.4ms in a straight line thro.pdfarjuncp10
 
You have a rural dial-up customer who complains that a large number .pdf
You have a rural dial-up customer who complains that a large number .pdfYou have a rural dial-up customer who complains that a large number .pdf
You have a rural dial-up customer who complains that a large number .pdfarjuncp10
 
You are given a mixed culture containing a anaerobic thermophile, ae.pdf
You are given a mixed culture containing a anaerobic thermophile, ae.pdfYou are given a mixed culture containing a anaerobic thermophile, ae.pdf
You are given a mixed culture containing a anaerobic thermophile, ae.pdfarjuncp10
 
Woyld removing phenylethyl alcohol from PEA alter the mediumsS.pdf
Woyld removing phenylethyl alcohol from PEA alter the mediumsS.pdfWoyld removing phenylethyl alcohol from PEA alter the mediumsS.pdf
Woyld removing phenylethyl alcohol from PEA alter the mediumsS.pdfarjuncp10
 
Which abstraction uses slates, state transitions, inputs and outputs .pdf
Which abstraction uses slates, state transitions, inputs and outputs .pdfWhich abstraction uses slates, state transitions, inputs and outputs .pdf
Which abstraction uses slates, state transitions, inputs and outputs .pdfarjuncp10
 
What is the target cell for the hormone AngiotensionogenSolut.pdf
What is the target cell for the hormone AngiotensionogenSolut.pdfWhat is the target cell for the hormone AngiotensionogenSolut.pdf
What is the target cell for the hormone AngiotensionogenSolut.pdfarjuncp10
 

More from arjuncp10 (20)

I l Show that if X has the discrete topology, then its only conn.pdf
I l Show that if X has the discrete topology, then its only conn.pdfI l Show that if X has the discrete topology, then its only conn.pdf
I l Show that if X has the discrete topology, then its only conn.pdf
 
In 2006 the CEO of Bear Sterns, James Caynes, received a compensatio.pdf
In 2006 the CEO of Bear Sterns, James Caynes, received a compensatio.pdfIn 2006 the CEO of Bear Sterns, James Caynes, received a compensatio.pdf
In 2006 the CEO of Bear Sterns, James Caynes, received a compensatio.pdf
 
How would a CFE devise a plan to prevent subsequent employee fraud.pdf
How would a CFE devise a plan to prevent subsequent employee fraud.pdfHow would a CFE devise a plan to prevent subsequent employee fraud.pdf
How would a CFE devise a plan to prevent subsequent employee fraud.pdf
 
Hilary rode her horse for 8 miles until it was hurt.Then she walked .pdf
Hilary rode her horse for 8 miles until it was hurt.Then she walked .pdfHilary rode her horse for 8 miles until it was hurt.Then she walked .pdf
Hilary rode her horse for 8 miles until it was hurt.Then she walked .pdf
 
fully comments for my program, thank you will thumb up#include io.pdf
fully comments for my program, thank you will thumb up#include io.pdffully comments for my program, thank you will thumb up#include io.pdf
fully comments for my program, thank you will thumb up#include io.pdf
 
Find the admittance Yab in the circuit seen in the figure. Take that.pdf
Find the admittance Yab in the circuit seen in the figure. Take that.pdfFind the admittance Yab in the circuit seen in the figure. Take that.pdf
Find the admittance Yab in the circuit seen in the figure. Take that.pdf
 
Diversity Paper Each student will complete a diversity research assig.pdf
Diversity Paper Each student will complete a diversity research assig.pdfDiversity Paper Each student will complete a diversity research assig.pdf
Diversity Paper Each student will complete a diversity research assig.pdf
 
Detailed solutions please 1. Let R and S be commutative rings and le.pdf
Detailed solutions please 1. Let R and S be commutative rings and le.pdfDetailed solutions please 1. Let R and S be commutative rings and le.pdf
Detailed solutions please 1. Let R and S be commutative rings and le.pdf
 
Describe the mechanisms of asexual reproduction inProkaryotesPr.pdf
Describe the mechanisms of asexual reproduction inProkaryotesPr.pdfDescribe the mechanisms of asexual reproduction inProkaryotesPr.pdf
Describe the mechanisms of asexual reproduction inProkaryotesPr.pdf
 
Define intermediate phenotype and then imagine some intermediate phe.pdf
Define intermediate phenotype and then imagine some intermediate phe.pdfDefine intermediate phenotype and then imagine some intermediate phe.pdf
Define intermediate phenotype and then imagine some intermediate phe.pdf
 
Consider a population of lizards living on the coast of Africa. A sto.pdf
Consider a population of lizards living on the coast of Africa. A sto.pdfConsider a population of lizards living on the coast of Africa. A sto.pdf
Consider a population of lizards living on the coast of Africa. A sto.pdf
 
Can “discovery science” (for example, the discovery of a new species.pdf
Can “discovery science” (for example, the discovery of a new species.pdfCan “discovery science” (for example, the discovery of a new species.pdf
Can “discovery science” (for example, the discovery of a new species.pdf
 
C++Write a function void headEnqueue(Queue q, int key) which enqu.pdf
C++Write a function void headEnqueue(Queue q, int key) which enqu.pdfC++Write a function void headEnqueue(Queue q, int key) which enqu.pdf
C++Write a function void headEnqueue(Queue q, int key) which enqu.pdf
 
All of the following are features or functions of nanobodies except _.pdf
All of the following are features or functions of nanobodies except _.pdfAll of the following are features or functions of nanobodies except _.pdf
All of the following are features or functions of nanobodies except _.pdf
 
A girl running at a constant speed of 1.4ms in a straight line thro.pdf
A girl running at a constant speed of 1.4ms in a straight line thro.pdfA girl running at a constant speed of 1.4ms in a straight line thro.pdf
A girl running at a constant speed of 1.4ms in a straight line thro.pdf
 
You have a rural dial-up customer who complains that a large number .pdf
You have a rural dial-up customer who complains that a large number .pdfYou have a rural dial-up customer who complains that a large number .pdf
You have a rural dial-up customer who complains that a large number .pdf
 
You are given a mixed culture containing a anaerobic thermophile, ae.pdf
You are given a mixed culture containing a anaerobic thermophile, ae.pdfYou are given a mixed culture containing a anaerobic thermophile, ae.pdf
You are given a mixed culture containing a anaerobic thermophile, ae.pdf
 
Woyld removing phenylethyl alcohol from PEA alter the mediumsS.pdf
Woyld removing phenylethyl alcohol from PEA alter the mediumsS.pdfWoyld removing phenylethyl alcohol from PEA alter the mediumsS.pdf
Woyld removing phenylethyl alcohol from PEA alter the mediumsS.pdf
 
Which abstraction uses slates, state transitions, inputs and outputs .pdf
Which abstraction uses slates, state transitions, inputs and outputs .pdfWhich abstraction uses slates, state transitions, inputs and outputs .pdf
Which abstraction uses slates, state transitions, inputs and outputs .pdf
 
What is the target cell for the hormone AngiotensionogenSolut.pdf
What is the target cell for the hormone AngiotensionogenSolut.pdfWhat is the target cell for the hormone AngiotensionogenSolut.pdf
What is the target cell for the hormone AngiotensionogenSolut.pdf
 

Recently uploaded

Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 

Recently uploaded (20)

Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 

1. Add a breadth-first (level-order) traversal function to the binar.pdf

  • 1. 1. Add a breadth-first (level-order) traversal function to the binary tree code. 2. Add a function to find the height of a tree. 3. Re-implement one of the depth-first traversal methods using a stack instead of recursion. 4. Add a link to each nodes parent node. #include #include #include using namespace std; template < typename T > class TreeNode { public: T element; // TreeNode < T > * left; // TreeNode < T > * right; // TreeNode * next; TreeNode() // { left = NULL; next = NULL; } TreeNode(T element) // Constructor { this->element = element; left = NULL; right = NULL; } }; template < typename T > class BinaryTree { public: BinaryTree(); BinaryTree(T elements[], int arraySize);
  • 2. bool insert(T element); void inorder(); void preorder(); void postorder(); int getSize(); bool search(T element); void breadthFirstTraversal(); int depth(); private: TreeNode < T > * root; int size; void inorder(TreeNode < T > * root); void postorder(TreeNode < T > * root); void preorder(TreeNode < T > * root); bool search(T element, TreeNode < T > * root); int depth(TreeNode * root); }; template < typename T > BinaryTree < T >::BinaryTree() { root = NULL; size = 0; } template < typename T > BinaryTree < T >::BinaryTree(T elements[], int arraySize) { root = NULL; size = 0; for (int i = 0; i < arraySize; i++) { insert(elements[i]); } } template < typename T > bool BinaryTree < T >::insert(T element) {
  • 3. if (root == NULL) root = new TreeNode < T > (element); // Create a new root else { // Locate the parent node TreeNode < T > * parent = NULL; TreeNode < T > * current = root; while (current != NULL) if (element < current->element) { parent = current; current = current->left; } else if (element > current->element) { parent = current; current = current->right; } else return false; // Duplicate node not inserted // Create the new node and attach it to the parent node if (element < parent->element) parent->left = new TreeNode < T > (element); else parent->right = new TreeNode < T > (element); } size++; return true; // Element inserted } /* Inorder traversal */ template < typename T > void BinaryTree < T >::inorder() { inorder(root); } /* Inorder traversal from a subtree */
  • 4. template < typename T > void BinaryTree < T >::inorder(TreeNode < T > * root) { if (root == NULL) return; inorder(root->left); cout << root->element << " "; inorder(root->right); } /* Postorder traversal */ template < typename T > void BinaryTree < T >::postorder() { postorder(root); } /** Inorder traversal from a subtree */ template < typename T > void BinaryTree < T >::postorder(TreeNode < T > * root) { if (root == NULL) return; postorder(root->left); postorder(root->right); cout << root->element << " "; } /* */ template < typename T > void BinaryTree < T >::preorder() { preorder(root); } /* */ template < typename T > void BinaryTree < T >::preorder(TreeNode < T > * root) { if (root == NULL) return; cout << root->element << " "; preorder(root->left);
  • 5. preorder(root->right); } /**/ template < typename T > int BinaryTree < T >::getSize() { return size; } template < typename T > bool BinaryTree < T >::search(T element) { return search(element, root); } template < typename T > bool BinaryTree < T >::search(T element, TreeNode < T > * root) { if (root == NULL) return false; else if (root->element == element) return true; else if (root->element > element) return search(element, root->right); else return search(element, root->left); } int main() { BinaryTree < string > tree1; tree1.insert("George"); tree1.insert("Michael"); tree1.insert("Tom"); tree1.insert("Adam"); tree1.insert("Jones"); tree1.insert("Peter"); tree1.insert("Daniel");
  • 6. cout << "Inorder (sorted): "; tree1.inorder(); cout << " Postorder: "; tree1.postorder(); cout << " Preorder: "; tree1.preorder(); cout << " The number of nodes is " << tree1.getSize(); int numbers[] = { 2, 4, 3, 1, 8, 5, 6, 7 }; BinaryTree < int > tree2(numbers, 8); cout << " Inorder (sorted): "; tree2.inorder(); cout << " search 2 " << tree2.search(2) << endl; cout << " search 99 " << tree2.search(99) << endl; cout << " search 8 " << tree2.search(8) << endl; return 0; } Solution #include #include #include using namespace std; template < typename T > class TreeNode { public: T element; // TreeNode < T > * left; // TreeNode < T > * right; // TreeNode * next; TreeNode() // {
  • 7. left = NULL; next = NULL; } TreeNode(T element) // Constructor { this->element = element; left = NULL; right = NULL; } }; template < typename T > class BinaryTree { public: BinaryTree(); BinaryTree(T elements[], int arraySize); bool insert(T element); void inorder(); void preorder(); void postorder(); int getSize(); bool search(T element); void breadthFirstTraversal(); int depth(); void BFS(); private: TreeNode < T > * root; int size; void inorder(TreeNode < T > * root); void postorder(TreeNode < T > * root); void preorder(TreeNode < T > * root); bool search(T element, TreeNode < T > * root); int depth(TreeNode * root); void printLevelOrder(TreeNode < T > * root); void printGivenLevel(TreeNode < T > * root, int level);
  • 8. }; template < typename T > int BinaryTree < T >::depth() { depth(root); } template < typename T > void BinaryTree < T >::BFS() { printLevelOrder(root); } template < typename T > void BinaryTree < T >::printLevelOrder(TreeNode < T > * root) { int h = depth(root); int i; for (i=1; i<=h; i++) printGivenLevel(root, i); } /* Print nodes at a given level */ template < typename T > void BinaryTree < T >::printGivenLevel(TreeNode < T > * root, int level) { if (root == NULL) return; if (level == 1) cout<<" "<element; else if (level > 1) { printGivenLevel(root->left, level-1); printGivenLevel(root->right, level-1); } } template < typename T > int BinaryTree < T >::depth(TreeNode < T > * element)
  • 9. { if (element==NULL) return 0; else { int lDepth = depth(element->left); int rDepth = depth(element->right); // use the larger one if (lDepth > rDepth) return(lDepth+1); else return(rDepth+1); } } template < typename T > BinaryTree < T >::BinaryTree() { root = NULL; size = 0; } template < typename T > BinaryTree < T >::BinaryTree(T elements[], int arraySize) { root = NULL; size = 0; for (int i = 0; i < arraySize; i++) { insert(elements[i]); } } template < typename T > bool BinaryTree < T >::insert(T element) { if (root == NULL)
  • 10. root = new TreeNode < T > (element); // Create a new root else { // Locate the parent node TreeNode < T > * parent = NULL; TreeNode < T > * current = root; while (current != NULL) if (element < current->element) { parent = current; current = current->left; } else if (element > current->element) { parent = current; current = current->right; } else return false; // Duplicate node not inserted // Create the new node and attach it to the parent node if (element < parent->element) parent->left = new TreeNode < T > (element); else parent->right = new TreeNode < T > (element); } size++; return true; // Element inserted } /* Inorder traversal */ template < typename T > void BinaryTree < T >::inorder() { inorder(root); } /* Inorder traversal from a subtree */ template < typename T >
  • 11. void BinaryTree < T >::inorder(TreeNode < T > * root) { if (root == NULL) return; inorder(root->left); cout << root->element << " "; inorder(root->right); } /* Postorder traversal */ template < typename T > void BinaryTree < T >::postorder() { postorder(root); } /** Inorder traversal from a subtree */ template < typename T > void BinaryTree < T >::postorder(TreeNode < T > * root) { if (root == NULL) return; postorder(root->left); postorder(root->right); cout << root->element << " "; } /* */ template < typename T > void BinaryTree < T >::preorder() { preorder(root); } /* */ template < typename T > void BinaryTree < T >::preorder(TreeNode < T > * root) { if (root == NULL) return; cout << root->element << " "; preorder(root->left); preorder(root->right);
  • 12. } /**/ template < typename T > int BinaryTree < T >::getSize() { return size; } template < typename T > bool BinaryTree < T >::search(T element) { return search(element, root); } template < typename T > bool BinaryTree < T >::search(T element, TreeNode < T > * root) { if (root == NULL) return false; else if (root->element == element) return true; else if (root->element > element) return search(element, root->right); else return search(element, root->left); } int main() { BinaryTree < string > tree1; tree1.insert("George"); tree1.insert("Michael"); tree1.insert("Tom"); tree1.insert("Adam"); tree1.insert("Jones"); tree1.insert("Peter"); tree1.insert("Daniel"); cout << "Inorder (sorted): "; tree1.inorder();
  • 13. cout << " Postorder: "; tree1.postorder(); cout << " Preorder: "; tree1.preorder(); cout << " The number of nodes is " << tree1.getSize(); int numbers[] = { 2, 4, 3, 1, 8, 5, 6, 7 }; BinaryTree < int > tree2(numbers, 8); cout << " Inorder (sorted): "; tree2.inorder(); cout << " search 2 " << tree2.search(2) << endl; cout << " search 99 " << tree2.search(99) << endl; cout << " search 8 " << tree2.search(8) << endl; cout<<"Height is "<