This C Program Finds the Sum of all Nodes in a Tree such that any node is sum of values at left and right sub tree.
Here is source code of the C Program to Find the Sum of all Nodes in a Tree such that any node is sum of values at left and right sub tree. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C Program to Find the Sum of all Nodes in a Tree
*
* 50
* / \
* 20 30
* / \
* 70 80
* / \ \
* 10 40 60
*
*/
#include <stdio.h>
#include <stdlib.h>
struct btnode
{
int value;
struct btnode *l;
struct btnode *r;
}*root = NULL, *ptr, *temp;
// Function Prototypes
int find_depth(struct btnode *);
int modify_tree(struct btnode *);
void printout(struct btnode *);
struct btnode* newnode(int);
void main()
{
int d;
root = newnode(50);
root->l = newnode(20);
root->r = newnode(30);
root->l->l = newnode(70);
root->l->r = newnode(80);
root->l->r->r = newnode(60);
root->l->l->l = newnode(10);
root->l->l->r = newnode(40);
printout(root);
ptr = root;
d = find_depth(ptr);
printf("Depth of tree is %d\n",d);
printf("tree elements after modification are ----\n");
modify_tree(ptr);
printout(ptr);
}
// Create a node
struct btnode* newnode(int value)
{
struct btnode* node = (struct btnode*)malloc(sizeof(struct btnode));
node->value = value;
node->l = NULL;
node->r = NULL;
return(node);
}
// Function to find depth of a tree
int find_depth(struct btnode* tree)
{
int ldepth, rdepth;
if (tree == NULL)
return 0;
else
{
ldepth = find_depth(tree->l);
rdepth = find_depth(tree->r);
if (ldepth > rdepth)
return ldepth + 1;
else
return rdepth + 1;
}
}
// Function to modify the tree
int modify_tree(struct btnode *tree)
{
int i, original;
if (tree == NULL)
return 0;
original = tree->value;
tree->value = modify_tree(tree->l) + modify_tree(tree->r);
return tree->value + original;
}
// Function to print the elements of tree
void printout(struct btnode *tree)
{
if (tree->l)
printout(tree->l);
printf("%d\n", tree->value);
if (tree->r)
printout(tree->r);
}
$ gcc tree37.c $ a.out 10 70 40 20 80 60 50 30 Depth of tree is 4 tree elements after modification are ---- 0 50 0 260 60 0 310 0
Sanfoundry Global Education & Learning Series – 1000 C Programs.
advertisement
advertisement
Here’s the list of Best Books in C Programming, Data-Structures and Algorithms
If you wish to look at programming examples on all topics, go to C Programming Examples.
Related Posts:
- Check Programming Books
- Practice Programming MCQs
- Apply for Computer Science Internship
- Practice Design & Analysis of Algorithms MCQ
- Practice Computer Science MCQs