SlideShare a Scribd company logo
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 .docx
debishakespeare
 
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
meerobertsonheyde608
 
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
shanki7
 
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
 
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
nipuns1983
 
Doublylinklist
DoublylinklistDoublylinklist
Doublylinklistritu1806
 
Linked lists
Linked listsLinked lists
Linked lists
George Scott IV
 
BinarySearchTrees.ppt
BinarySearchTrees.pptBinarySearchTrees.ppt
BinarySearchTrees.ppt
SARATHGARIKINA
 
BinarySearchTrees.ppt
BinarySearchTrees.pptBinarySearchTrees.ppt
BinarySearchTrees.ppt
ItsStranger1
 
BinarySearchTrees (1).ppt
BinarySearchTrees (1).pptBinarySearchTrees (1).ppt
BinarySearchTrees (1).ppt
plagcheck
 
Binary searchtrees
Binary searchtreesBinary searchtrees
Binary searchtrees
HasnainBaloch12
 
BinarySearchTrees.ppt
BinarySearchTrees.pptBinarySearchTrees.ppt
BinarySearchTrees.ppt
plagcheck
 
data structure very BinarySearchTrees.ppt
data structure very BinarySearchTrees.pptdata structure very BinarySearchTrees.ppt
data structure very BinarySearchTrees.ppt
DharmannaRathod1
 
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
illyasraja7
 
Linked lists
Linked listsLinked 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
info750646
 
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptx
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptxData Structures and Agorithm: DS 14 Binary Expression Tree.pptx
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptx
RashidFaridChishti
 
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
manjan6
 
Lab Week 2 Game Programming.docx
Lab Week 2 Game Programming.docxLab Week 2 Game Programming.docx
Lab Week 2 Game Programming.docx
teyaj1
 

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
 
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptx
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptxData Structures and Agorithm: DS 14 Binary Expression Tree.pptx
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptx
 
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
 

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.pdf
arjuncp10
 
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
arjuncp10
 
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
arjuncp10
 
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
arjuncp10
 
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
arjuncp10
 
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
arjuncp10
 
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
arjuncp10
 
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
arjuncp10
 
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
arjuncp10
 
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
arjuncp10
 
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
arjuncp10
 
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
arjuncp10
 
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
arjuncp10
 
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
arjuncp10
 
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
arjuncp10
 
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
arjuncp10
 
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
arjuncp10
 
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
arjuncp10
 
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
arjuncp10
 
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
arjuncp10
 

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

Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
AzmatAli747758
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
PedroFerreira53928
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
Steve Thomason
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
Fundacja Rozwoju Społeczeństwa Przedsiębiorczego
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
EduSkills OECD
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
Celine George
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
bennyroshan06
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
Col Mukteshwar Prasad
 

Recently uploaded (20)

Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
 

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