Sum of all the grandchild nodes of binary tree in c

C program for Sum of all the grandchild nodes of binary tree. Here more solutions.
// Include header file
#include <stdio.h>
#include <stdlib.h>
/*
C program for
Sum of nodes in binary tree whose grandparents exists
*/
// Binary Tree node
typedef struct TreeNode
{
// Define useful field of TreeNode
int data;
struct TreeNode * left;
struct TreeNode * right;
}TreeNode;
TreeNode * getTreeNode(int data)
{
// Create dynamic memory of TreeNode
TreeNode * ref = (TreeNode * ) malloc(sizeof(TreeNode));
if (ref == NULL)
{
// Failed to create memory
return NULL;
}
// Set node value
ref->data = data;
ref->left = NULL;
ref->right = NULL;
return ref;
}
typedef struct BinaryTree
{
// Define useful field of BinaryTree
struct TreeNode * root;
}BinaryTree;
BinaryTree * getBinaryTree()
{
// Create dynamic memory of BinaryTree
BinaryTree * ref = (BinaryTree * ) malloc(sizeof(BinaryTree));
if (ref == NULL)
{
// Failed to create memory
return NULL;
}
// Set initial tree root
ref->root = NULL;
return ref;
}
void preOrder(TreeNode * node)
{
if (node != NULL)
{
// Print node value
printf(" %d", node->data);
// Visit left subtree
preOrder(node->left);
// Visit right subtree
preOrder(node->right);
}
}
int grandchildSum(TreeNode * node, int level)
{
if (node != NULL)
{
int result = 0;
if (level > 2)
{
// Get the node
result = node->data;
}
// Visit left subtree and right subtree
return result +
grandchildSum(node->left, level + 1) +
grandchildSum(node->right, level + 1);
}
else
{
return 0;
}
}
int main()
{
// Create new binary trees
BinaryTree * tree = getBinaryTree();
/*
4
/ \
/ \
12 7
/ \ \
2 3 1
/ \ /
6 8 5
/
9
----------------
Constructing binary tree
*/
// Add nodes
tree->root = getTreeNode(4);
tree->root->left = getTreeNode(12);
tree->root->left->right = getTreeNode(3);
tree->root->left->right->left = getTreeNode(6);
tree->root->left->right->left->left = getTreeNode(9);
tree->root->left->right->right = getTreeNode(8);
tree->root->left->left = getTreeNode(2);
tree->root->right = getTreeNode(7);
tree->root->right->right = getTreeNode(1);
tree->root->right->right->left = getTreeNode(5);
// Display tree node
printf("\n Tree Nodes ");
preOrder(tree->root);
// Find node sum
// 2 + 3 + 6 + 9 + 8 + 1 + 5 = 34
int result = grandchildSum(tree->root, 1);
// Display result
printf("\n Result : %d", result);
}
Output
Tree Nodes 4 12 2 3 6 9 8 7 1 5
Result : 34
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment