5. Write a recursive function sumTreeNodeHelper that sums the elements of a bina
ID: 3734423 • Letter: 5
Question
5. Write a recursive function sumTreeNodeHelper that sums the elements of a binary search tree starting with the smallest element and adding elements in order up to the largest element and prints the running sum as each new value (ie. Node->val) is added to the sum (We're assuming double values are stored in the tree). (6 pts) You will not use an iterator. void sum TreeNodeHelper(struct BNode "node, double *sum) void sum Tree(struct BSTree "tree, double *sum) sum TreeNodeHelper(tree->root, sum);Explanation / Answer
// C Program to Construct a Binary Search Tree and compute total elements sum
#include <stdio.h>
#include <stdlib.h>
struct btnode
{
int value;
struct btnode *l;
struct btnode *r;
}*root = NULL, *temp = NULL, *t2, *t1;
void insert();
void create();
void search(struct btnode *t);
double sumBT(struct btnode *t);
int flag = 1;
void main()
{
int ch;
double x;
printf(" ---Choose Operation --- ");
printf("1 - Insert an element into tree ");
printf("2 - Sum of all elements ");
printf("3 - Exit ");
while(1)
{
printf(" Enter your choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
insert();
break;
case 2:
x = sumBT(root);
printf("The sum of all BST elements is %lf ",x);
break;
case 3:
exit(0);
default :
printf("Wrong choice, Please enter correct choice ");
break;
}
}
}
// Recursive function to add all binary search tree elements
double sumBT(struct btnode *t){
if(t == NULL)
return 0;
return(t->value + sumBT(t->l) + sumBT(t->r) );
}
/* To insert a node in the tree */
void insert()
{
create();
if (root == NULL)
root = temp;
else
search(root);
}
/* To create a node */
void create()
{
int data;
printf("Enter data : ");
scanf("%d", &data);
temp = (struct btnode *)malloc(1*sizeof(struct btnode));
temp->value = data;
temp->l = temp->r = NULL;
}
/* Function to search the appropriate position to insert the new node */
void search(struct btnode *t)
{
if ((temp->value > t->value) && (t->r != NULL)) /* value more than root node value insert at right */
search(t->r);
else if ((temp->value > t->value) && (t->r == NULL))
t->r = temp;
else if ((temp->value < t->value) && (t->l != NULL)) /* value less than root node value insert at left */
search(t->l);
else if ((temp->value < t->value) && (t->l == NULL))
t->l = temp;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.