In this program, we are going to share a C program to find the sum of all nodes in a tree. If you are a beginner and want to start learning the C programming, then keep your close attention in this tutorial as I am going to share a C program to find the sum of all nodes in a tree with the output.
We have designed this program for beginners for learning purpose. Copy below c program and execute it with c compiler to see the output of the program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | #include <stdio.h> #include <stdlib.h> struct btnode { int value; struct btnode *l; struct btnode *r; }*root = NULL, *ptr, *temp; 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); } 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); } 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; } } 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; } void printout(struct btnode *tree) { if (tree->l) printout(tree->l); printf("%d\n", tree->value); if (tree->r) printout(tree->r); } |
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
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.