SlideShare a Scribd company logo
Tree Traversals
A tree traversal is the process of "visiting" each node of a tree in some particular order. For a
binary search tree, we can talk about an inorder traversal and a preorder traversal. For this
assignment you are to implement both of these traversals in the code that was started in class.
File bstree.h contains the BSTree class that was developed during class (with the addition of
comments which were omitted by your instructor due to time constraints). The class contains two
inorder functions, one public and one private, and two preorder functions, also one public and one
private. As was the case with other functions implemented for this class, the public versions of
these functions simply call the private versions passing the root node (pointer) as a parameter.
The private versions carry out their actions on the subtree rooted at the given node.
The code provided in bstree.h is missing the implementations for the private inorder and preorder
functions. The coding part of this assignment is to implement these two functions.
When completed, the test program provided should produce the following output:
Values stored in the tree are:
bird
cat
deer
dog
giraffe
groundhog
horse
snake
turtle
The structure of the tree is as follows:
dog
-bird
--cat
---deer
-turtle
--giraffe
---snake
----groundhog
-----horse
Copied!
Written Part
In addition to the coding noted above, give an analysis of all public member functions of the class,
including all constructors, the destructor, and the overload of the assignment operator. For your
analysis you may assume a well-balanced tree (whereas a lopsided tree might lead to a different
analysis).
bstree.h
#pragma once
// A Binary Search Tree implementation.
template <typename T>
class BSTree {
private:
// A node in the tree. Each node has pointers to its left and right nodes
// as well as its parent. When a node is created, the parent and data item
// must be provided.
class node {
public:
T data;
node* left;
node* right;
node* parent;
node (const T& d, node* p) {
parent = p;
data = d;
left = right = nullptr;
}
};
// Pointer to the root node. Initially this is null for an empty tree.
node* root;
// Copy the subtree of another BSTree object into this object. Used by
// the copy constructor and assignment operator.
void copy (node* p) {
if (p) { // If p points to a node...
insert(p->data); // Insert data item
copy(p->left); // Copy the left subtree
copy(p->right); // Copy the right subtree
}
}
// Destroy a node and all nodes in both subtrees. Called by the
// destructor.
void destroy (node* p) {
if (p) { // If p is not null...
destroy(p->left); // Destroy the left subtree
destroy(p->right); // Destroy the right subtree
delete p; // Destroy the node
}
}
// Helper function to determine if a data value is contained in the tree.
// Takes the data value being searched and a pointer to the node in the
// tree. Returns pointer to node in which data item is found, a null
// pointer otherwise.
node* find (const T& d, node* p) const {
// Given: p is a pointer to an existing node
if (d == p->data) // Is this the value we're looking for?
return p;
if (d < p->data) // Check left side, if null then not found
return p->left ? find(d, p->left) : nullptr;
return p->right ? find(d, p->right) : nullptr; // Check right side...
}
// Helper function to insert a data item into the tree. Takes the data
// and a pointer to a node in the tree. Recursively decends down the tree
// until position were insertion should take place is found.
void insert (const T& d, node* p) {
// Given: p is a pointer to an existing node (root of a subtree)
if (d < p->data) { // Insert into left subtree?
if (p->left) // Left subtree exists?
insert(d, p->left); // Insert into left subtree...
else // No left subtree, insert the new node
p->left = new node(d, p);
}
else if (d > p->data) { // Insert into right subtree?
if (p->right) // Right subtree exists?
insert(d, p->right); // Insert into right subtree...
else // No right subtree, insert the new node
p->right = new node(d, p);
}
// else: node p has data value being inserted, ignore (no dups allowed)
}
// An inorder traversal for a subtree rooted at node p. Performs an
// inorder traversal on the left subtree, then calls f for the data item
// at p, then performs an inorder traversal on the right subtree.
template <typename U>
void inorder (node* p, U f) const {
// TODO: Complete this function.
}
// A preorder traversal for a subtree rooted at node p. Calls f for the
// data item at p with the given depth, then performs a preorder
// traversal on the left and right subtrees passing the depth plus 1.
template <typename U>
void preorder (node* p, U f, int depth) const {
// TODO: Complete this function.
}
public:
// Constructor, initializes an empty tree by setting the root pointer to
// null.
BSTree() { root = nullptr; }
// Copy constructor
BSTree(const BSTree& t) { root = nullptr; copy(t.root); }
// Assignment overload
BSTree& operator= (const BSTree& t) {
destroy(root); // Destroy the current tree
root = nullptr; // Initialize root pointer
copy(t.root); // Copy the tree
}
// Destructor, destroys all nodes
~BSTree() { destroy(root); }
// Find a data item in the tree. Return true if data value exists,
// otherwise return false. Calls recursive find helper function.
bool find (const T& d) const {
return root && find(d, root);
}
// Insert a new data item into the tree. If the data item already exists,
// it is ignored (no duplicates are added). Calls recursive insert helper
// function.
void insert (const T& d) {
if (!root) // Is tree empty?
root = new node(d, nullptr); // Create root node
else if (d < root->data) { // Add new value to left side?
if (root->left) // Is there is a left subtree?
insert(d, root->left); // Insert into left subtree...
else // No left subtree, create node on left side
root->left = new node(d, root);
}
else if (d > root->data) { // Add new value to right side?
if (root->right) // Is there a right subtree?
insert(d, root->right); // Insert into right subtree...
else // No right subtree, create node on right side
root->right = new node(d, root);
}
}
// Perform an inorder traversal using function f. Calls the recursive
// helper function.
template <typename U>
void inorder (U f) const { inorder(root, f); }
// Perform a preorder traversal using function f. Calls the recursive
// helper function. Note that function f requires a second parameter
// which is the depth.
template <typename U>
void preorder (U f) const { preorder(root, f, 0); }
};

More Related Content

PDF
MAINCPP include ltiostreamgt include ltstringgt u.pdf
PDF
1. Add a breadth-first (level-order) traversal function to the binar.pdf
PDF
Implement a function TNode copy_tree(TNode t) that creates a copy .pdf
PDF
main.cpp#include TreeNode.h GIVEN void inorderTraversal(.pdf
PDF
Please write the C++ code that would display the exact same output a.pdf
PPTX
Binary tree
DOCX
Biary search Tree.docx
PDF
Data StructuresPlease I need help completing this c++ program..pdf
MAINCPP include ltiostreamgt include ltstringgt u.pdf
1. Add a breadth-first (level-order) traversal function to the binar.pdf
Implement a function TNode copy_tree(TNode t) that creates a copy .pdf
main.cpp#include TreeNode.h GIVEN void inorderTraversal(.pdf
Please write the C++ code that would display the exact same output a.pdf
Binary tree
Biary search Tree.docx
Data StructuresPlease I need help completing this c++ program..pdf

Similar to Tree Traversals A tree traversal is the process of visiting.pdf (20)

PDF
Add these three functions to the class binaryTreeType (provided).W.pdf
PPTX
UNIT 2 TREES & GRAPH COMPLETE NOTES OF DATA STRUCTURE
DOCX
Assg 12 Binary Search TreesCOSC 2336 Spring 2019April.docx
PPT
Algorithm and Data Structure - Binary Trees
DOCX
Binary Tree in C++ coding in the data structure
PDF
Tree and binary tree
PDF
I have C++ question that I do not know how to do, Can you teach me t.pdf
PPTX
Data structures and Algorithm analysis_Lecture4.pptx
PPTX
TREE DATA STRUCTURE SLIDES dsa dsa .pptx
PPTX
BST.pptx this is Good for data structure
PPTX
BST.pptx this isp used for learning binary search trees
PDF
In c++ format, for each function in the code, please using the comme.pdf
PDF
Binary Tree - Algorithms
PPTX
PPTX
PDF
Unit iv data structure-converted
PPT
17 Trees.ppt DSADSADSADSADSADSADSADSADSA
PDF
Lecture notes data structures tree
PDF
C++, Implement the class BinarySearchTree, as given in listing 16-4 .pdf
PPT
Binary trees
Add these three functions to the class binaryTreeType (provided).W.pdf
UNIT 2 TREES & GRAPH COMPLETE NOTES OF DATA STRUCTURE
Assg 12 Binary Search TreesCOSC 2336 Spring 2019April.docx
Algorithm and Data Structure - Binary Trees
Binary Tree in C++ coding in the data structure
Tree and binary tree
I have C++ question that I do not know how to do, Can you teach me t.pdf
Data structures and Algorithm analysis_Lecture4.pptx
TREE DATA STRUCTURE SLIDES dsa dsa .pptx
BST.pptx this is Good for data structure
BST.pptx this isp used for learning binary search trees
In c++ format, for each function in the code, please using the comme.pdf
Binary Tree - Algorithms
Unit iv data structure-converted
17 Trees.ppt DSADSADSADSADSADSADSADSADSA
Lecture notes data structures tree
C++, Implement the class BinarySearchTree, as given in listing 16-4 .pdf
Binary trees

More from ajayadinathcomputers (20)

PDF
Turn the linked list implementation into a circular list Ha.pdf
PDF
Tu comedor tiene cuatro paredes un techo y un suelo Te gus.pdf
PDF
Tumor cell lines empressing NkGz2D lignds grow in CThdeplet.pdf
PDF
tssume a member is selected at random from the populaton rep.pdf
PDF
TrueFalse Mark the following statements as true T or fal.pdf
PDF
Translate the C code to MIPS assembly code Use a minimum nu.pdf
PDF
Truefalse Stack or heap or text or staticglobal data Stack.pdf
PDF
TRUEFALSE Write T if the statement is true and F .pdf
PDF
True or False The term drive time are during the times peop.pdf
PDF
Translate this function into MIPS assembly Remember the arg.pdf
PDF
True or False Four Asian Tigers Four Little Dragons we.pdf
PDF
True or False In Exercises 15 determine whether the state.pdf
PDF
True or False 1 If buyer refuses to accept conforming goods.pdf
PDF
True or false and explain1 Mr Viet use some of his income t.pdf
PDF
True or False Airway resistance decreases with parasympathe.pdf
PDF
True False Question 10 1 point The congruence class repres.pdf
PDF
Transcription 1 RNA vs DNA structure 2 Differentiate betwe.pdf
PDF
Trident Food Corporation en son mali yl iin aadaki gelir t.pdf
PDF
Tropical rain forests in Indonesia and South America receive.pdf
PDF
TRIPBAMs core produt development was an IT Dependant Strate.pdf
Turn the linked list implementation into a circular list Ha.pdf
Tu comedor tiene cuatro paredes un techo y un suelo Te gus.pdf
Tumor cell lines empressing NkGz2D lignds grow in CThdeplet.pdf
tssume a member is selected at random from the populaton rep.pdf
TrueFalse Mark the following statements as true T or fal.pdf
Translate the C code to MIPS assembly code Use a minimum nu.pdf
Truefalse Stack or heap or text or staticglobal data Stack.pdf
TRUEFALSE Write T if the statement is true and F .pdf
True or False The term drive time are during the times peop.pdf
Translate this function into MIPS assembly Remember the arg.pdf
True or False Four Asian Tigers Four Little Dragons we.pdf
True or False In Exercises 15 determine whether the state.pdf
True or False 1 If buyer refuses to accept conforming goods.pdf
True or false and explain1 Mr Viet use some of his income t.pdf
True or False Airway resistance decreases with parasympathe.pdf
True False Question 10 1 point The congruence class repres.pdf
Transcription 1 RNA vs DNA structure 2 Differentiate betwe.pdf
Trident Food Corporation en son mali yl iin aadaki gelir t.pdf
Tropical rain forests in Indonesia and South America receive.pdf
TRIPBAMs core produt development was an IT Dependant Strate.pdf

Recently uploaded (20)

PPTX
Cell Types and Its function , kingdom of life
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
RMMM.pdf make it easy to upload and study
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
Computing-Curriculum for Schools in Ghana
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Insiders guide to clinical Medicine.pdf
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
Pre independence Education in Inndia.pdf
Cell Types and Its function , kingdom of life
Renaissance Architecture: A Journey from Faith to Humanism
Final Presentation General Medicine 03-08-2024.pptx
O7-L3 Supply Chain Operations - ICLT Program
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
TR - Agricultural Crops Production NC III.pdf
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
RMMM.pdf make it easy to upload and study
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Computing-Curriculum for Schools in Ghana
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
102 student loan defaulters named and shamed – Is someone you know on the list?
O5-L3 Freight Transport Ops (International) V1.pdf
Insiders guide to clinical Medicine.pdf
2.FourierTransform-ShortQuestionswithAnswers.pdf
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Module 4: Burden of Disease Tutorial Slides S2 2025
Pre independence Education in Inndia.pdf

Tree Traversals A tree traversal is the process of visiting.pdf

  • 1. Tree Traversals A tree traversal is the process of "visiting" each node of a tree in some particular order. For a binary search tree, we can talk about an inorder traversal and a preorder traversal. For this assignment you are to implement both of these traversals in the code that was started in class. File bstree.h contains the BSTree class that was developed during class (with the addition of comments which were omitted by your instructor due to time constraints). The class contains two inorder functions, one public and one private, and two preorder functions, also one public and one private. As was the case with other functions implemented for this class, the public versions of these functions simply call the private versions passing the root node (pointer) as a parameter. The private versions carry out their actions on the subtree rooted at the given node. The code provided in bstree.h is missing the implementations for the private inorder and preorder functions. The coding part of this assignment is to implement these two functions. When completed, the test program provided should produce the following output: Values stored in the tree are: bird cat deer dog giraffe groundhog horse snake turtle The structure of the tree is as follows: dog -bird --cat ---deer -turtle --giraffe ---snake ----groundhog -----horse Copied! Written Part In addition to the coding noted above, give an analysis of all public member functions of the class, including all constructors, the destructor, and the overload of the assignment operator. For your analysis you may assume a well-balanced tree (whereas a lopsided tree might lead to a different analysis). bstree.h #pragma once // A Binary Search Tree implementation.
  • 2. template <typename T> class BSTree { private: // A node in the tree. Each node has pointers to its left and right nodes // as well as its parent. When a node is created, the parent and data item // must be provided. class node { public: T data; node* left; node* right; node* parent; node (const T& d, node* p) { parent = p; data = d; left = right = nullptr; } }; // Pointer to the root node. Initially this is null for an empty tree. node* root; // Copy the subtree of another BSTree object into this object. Used by // the copy constructor and assignment operator. void copy (node* p) { if (p) { // If p points to a node... insert(p->data); // Insert data item copy(p->left); // Copy the left subtree copy(p->right); // Copy the right subtree } } // Destroy a node and all nodes in both subtrees. Called by the // destructor. void destroy (node* p) { if (p) { // If p is not null... destroy(p->left); // Destroy the left subtree destroy(p->right); // Destroy the right subtree delete p; // Destroy the node } } // Helper function to determine if a data value is contained in the tree. // Takes the data value being searched and a pointer to the node in the // tree. Returns pointer to node in which data item is found, a null // pointer otherwise.
  • 3. node* find (const T& d, node* p) const { // Given: p is a pointer to an existing node if (d == p->data) // Is this the value we're looking for? return p; if (d < p->data) // Check left side, if null then not found return p->left ? find(d, p->left) : nullptr; return p->right ? find(d, p->right) : nullptr; // Check right side... } // Helper function to insert a data item into the tree. Takes the data // and a pointer to a node in the tree. Recursively decends down the tree // until position were insertion should take place is found. void insert (const T& d, node* p) { // Given: p is a pointer to an existing node (root of a subtree) if (d < p->data) { // Insert into left subtree? if (p->left) // Left subtree exists? insert(d, p->left); // Insert into left subtree... else // No left subtree, insert the new node p->left = new node(d, p); } else if (d > p->data) { // Insert into right subtree? if (p->right) // Right subtree exists? insert(d, p->right); // Insert into right subtree... else // No right subtree, insert the new node p->right = new node(d, p); } // else: node p has data value being inserted, ignore (no dups allowed) } // An inorder traversal for a subtree rooted at node p. Performs an // inorder traversal on the left subtree, then calls f for the data item // at p, then performs an inorder traversal on the right subtree. template <typename U> void inorder (node* p, U f) const { // TODO: Complete this function. } // A preorder traversal for a subtree rooted at node p. Calls f for the // data item at p with the given depth, then performs a preorder // traversal on the left and right subtrees passing the depth plus 1. template <typename U> void preorder (node* p, U f, int depth) const { // TODO: Complete this function. } public:
  • 4. // Constructor, initializes an empty tree by setting the root pointer to // null. BSTree() { root = nullptr; } // Copy constructor BSTree(const BSTree& t) { root = nullptr; copy(t.root); } // Assignment overload BSTree& operator= (const BSTree& t) { destroy(root); // Destroy the current tree root = nullptr; // Initialize root pointer copy(t.root); // Copy the tree } // Destructor, destroys all nodes ~BSTree() { destroy(root); } // Find a data item in the tree. Return true if data value exists, // otherwise return false. Calls recursive find helper function. bool find (const T& d) const { return root && find(d, root); } // Insert a new data item into the tree. If the data item already exists, // it is ignored (no duplicates are added). Calls recursive insert helper // function. void insert (const T& d) { if (!root) // Is tree empty? root = new node(d, nullptr); // Create root node else if (d < root->data) { // Add new value to left side? if (root->left) // Is there is a left subtree? insert(d, root->left); // Insert into left subtree... else // No left subtree, create node on left side root->left = new node(d, root); } else if (d > root->data) { // Add new value to right side? if (root->right) // Is there a right subtree? insert(d, root->right); // Insert into right subtree... else // No right subtree, create node on right side root->right = new node(d, root); } } // Perform an inorder traversal using function f. Calls the recursive // helper function. template <typename U> void inorder (U f) const { inorder(root, f); } // Perform a preorder traversal using function f. Calls the recursive
  • 5. // helper function. Note that function f requires a second parameter // which is the depth. template <typename U> void preorder (U f) const { preorder(root, f, 0); } };