Need to write the following functions in table.cpp, and add function prototypes
ID: 2246513 • Letter: N
Question
Need to write the following functions in table.cpp, and add function prototypes for them to table.h and invoke the functions in main.cpp.
* int sumOfNodes(node * root)
Recursively calculate the sum of all the nodes in the tree.
* void copyLeaf(node * src, node *& dest)
Recursively copy all the leaves from the source tree to the destination tree. The destination tree must be a binary search
tree.
--------------------------------------------------------------------------------------------
main.cpp
#include "table.h"
#include <iostream>
using namespace std;
int main()
{
node * root = NULL;
build(root);
display(root);
/* PLACE YOUR FUNCTION CALL HERE */
display(root);
destroy(root);
return 0;
}
-----------------------------------------------------------------
table.h
#ifndef TABLE_H
#define TABLE_H
//table.h
#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;
struct node
{
int data;
node * left;
node * right;;
};
void build(node * & root); //supplied
void display(node * root); //supplied
void destroy(node * & root); //supplied
/* ************** PLACE YOUR PROTOTYPE HERE ***************** */
#endif
------------------------------------------------------------
table.cpp
#include "table.h"
//Please put the impelementation of the required functions here
----------------------------------------------------------------------------------------
Please make sure the functions are done recursively, and are done in C++
Explanation / Answer
table.h
#include<cstdlib>
int sumOfNodes(node *);
void copyLeaf(node *, node **);
void insertion(int, node **);
node *makenode(int);
table.cpp
#include<cstdlib>
void insertion(int data, node **root)
{
if(*root == NULL)
*root = makenode(data);
if((*root)->data == data)
return;
else if((*root)->data > data)
{
if((*root)->left != NULL)
insertion(data, &(*root)->left);
else
(*root)->left = makenode(data);
}
else
{
if((*root)->right != NULL)
insertion(data, &(*root)->right);
else
(*root)->right = makenode(data);
}
}
void copyLeaf(node *src, node **dest)
{
if(src == NULL)
return;
if(src->left != NULL)
copyLeaf(src->left, dest);
if(src->right != NULL)
copyLeaf(src->right, dest);
if(src->left == NULL && src->right == NULL)
insertion(src->data, dest);
}
int sumOfNodes(node *root)
{
if(root == NULL)
return 0;
int i = 0, j = 0;
if(root->right != NULL)
i = sumOfNodes(root->right);
if(root->left != NULL)
j = sumOfNodes(root->left);
return (root->data + i + j);
}
node *makenode(int data)
{
node *temp = NULL;
temp = (node *)new(sizeof(node));
if(temp == NULL)
{
cout<<" Dynamic memory allocation failed ";
exit(-1);
}
temp->data = data, temp->right = temp->left = NULL;
return temp;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.