Difference between sums of odd level and even level nodes of a Binary Tree | GeeksforGeeks
Given a a Binary Tree, find the difference between the sum of nodes at odd level and the sum of nodes at even level. Consider root as level 1, left and right children of root as level 2 and so on.
We can recursively calculate the required difference as, value of root’s data subtracted by the difference for subtree under left child and the difference for subtree under right child.
Alternative way:
Given a a Binary Tree, find the difference between the sum of nodes at odd level and the sum of nodes at even level. Consider root as level 1, left and right children of root as level 2 and so on.
We can recursively calculate the required difference as, value of root’s data subtracted by the difference for subtree under left child and the difference for subtree under right child.
int
getLevelDiff(
struct
node *root)
{
// Base case
if
(root == NULL)
return
0;
// Difference for root is root's data - difference for left subtree
// - difference for right subtree
return
root->data - getLevelDiff(root->left) - getLevelDiff(root->right);
}
A straightforward method is to use level order traversal. In the traversal, check level of current node, if it is odd, increment odd sum by data of current node, otherwise increment even sum. Finally return difference between odd sum and even sum.
void levelDiff(node *root,int* diff,bool level)
{
if(level)
*diff += root -> data;
else
*diff -= root -> data;
{
if(level)
*diff += root -> data;
else
*diff -= root -> data;
if(root -> left)
levelDiff(root -> left,diff,!level);
if(root -> right)
levelDiff(root -> right,diff,!level);
}
Read full article from Difference between sums of odd level and even level nodes of a Binary Tree | GeeksforGeekslevelDiff(root -> left,diff,!level);
if(root -> right)
levelDiff(root -> right,diff,!level);
}