Sample Data Structures Questions Chapter 10 Trees provide a specific short answe
ID: 3721234 • Letter: S
Question
Sample Data Structures Questions
Chapter 10
Trees
provide a specific short answer for the below question in c++.
Using the binary_tree_node from Section 10.3, write a function to meet the following specification. You do not need to check the precondition. Make the function as efficient as possible (do not visit nodes unnecessarily):
template
size_t count42(binary_tree_node* root_ptr)
//Precondition: root_ptr is the root pointer of a binary SEARCH tree.
// Postcondition: The return value indicates how many times 42 appears in the tree.
Explanation / Answer
size_t count42(binary_tree_node* root_ptr)
{
// if the tree is empty
if( !root_ptr )
return 0;
// getVal() returns the value of the node
// getLeft() return the pointer to the left child
// getRight() return the pointer to the right child
// if the current node is 42
if( root_ptr->getVal() )
return 1 + count42( root->getLeft() ) + count42( root->getRight() );
// if the current node is not 42
else
return count42( root->getLeft() ) + count42( root->getRight() );
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.