3. (4 points) Write a Binary_Search_Tree member function sum that returns the su
ID: 3705195 • Letter: 3
Question
3. (4 points) Write a Binary_Search_Tree member function sum that returns the sum of the items in its tree. Assume that a default constructor and operator+ are defined for the item type T. If the tree is empty return the default constructed T item. (To call a default constructor without declaring a variable, just give the name of the default constructor with no arguments. E.g. return TO:) You should write a recursive helper function to do this. You also should assume that the code is in-lined into the template definition like the other member functions in bst.h.Explanation / Answer
int Sum(Node* parentRoot)
{
if (parentRoot == NULL)
return 0;
return (parentRoot->key + Sum(parentRoot->left) + Sum(parentRoot->right));// it will add both left and right side of tree nodes
}
int main() {
int totalSum = Sum(root);
cout << "Sum of all nodes in binary tree " << totalSum << endl;
}
Sample output:
Sum of all nodes in binary tree 40
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.