Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
Difference between sum of odd and even frequent elements in an Array
Next article icon

Difference between sums of odd level and even level nodes in an N-ary Tree

Last Updated : 21 Jun, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an N-ary Tree rooted at 1, the task is to find the difference between the sum of nodes at the odd level and the sum of nodes at even level.

Examples: 

Input:
                   4
               /  |   \
             2  3    -5
            / \       /  \
        -1   3   -2    6
Output: 10
Explanation:
Sum of nodes at even levels = 2 + 3 + (-5) = 0
Sum of nodes at odd levels = 4 + (-1) + 3 + (-2) + 6 = 10
Hence, the required difference is 10.

Input:       
              1
           / |  \
        2  -1  3
      /  \        \
    4    5        8
  /             / |    \
2            6  12   7  

Output: -13

Approach: To solve the problem, the idea is to find the respective sums of the nodes at the even and odd levels using Level Order Traversal and calculate the difference between them. Follow the steps below to solve the problem:

  • Initialize a Queue to store nodes and their respective levels.
  • Initialize variables evenSum and oddSum to store the sum of nodes at the even and odd levels respectively.
  • Push the root of the N-ary Tree along with its corresponding level, i.e., 1, into the Queue.   
  • Now, iterate and repeat the following steps until the Queue becomes empty:
    • Pop the nodes from the Queue. Store the level of the popped node in a variable, say currentLevel.
    • If currentLevel is even, add the value of the node to evenSum. Otherwise, add to oddSum.
    • Push all its children to the Queue and set their respective levels as currentLevel + 1.
  • Once the above steps are completed, calculate and print the difference between oddSum and evenSum.

Below is the implementation of the above approach:

C++




// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Structure of a node
// of an n-ary tree
struct Node {
    int val;
    vector<Node*> children;
};
 
// Function to create a
// new tree node
Node* newNode(int val)
{
    Node* temp = new Node;
    temp->val = val;
    return temp;
}
 
// Function to find the difference
// between of sums node values of
// odd and even levels in an N-ary tree
int evenOddLevelDifference(Node* root)
{
    // Store the sums of nodes at
    // even and odd levels
    int evenSum = 0, oddSum = 0;
 
    // Initialize a queue to store
    // pair of node and level
    queue<pair<Node*, int> > q;
 
    // Push the root into the
    // queue with level 1
    q.push({ root, 1 });
 
    // Iterate all levels
    // of tree are traversed
    while (!q.empty()) {
 
        // Store the node at the
        // front of the queue
        pair<Node*, int> currNode
            = q.front();
 
        // Pop the front node
        q.pop();
 
        // Store the current level
        int currLevel
            = currNode.second;
 
        // Store the current node value
        int currVal
            = currNode.first->val;
 
        // If current node
        // level is odd
        if (currLevel % 2)
 
            // Add to odd sum
            oddSum += currVal;
        else
 
            // Add to even sum
            evenSum += currVal;
 
        // Push all the children of current node
        // with increasing current level by 1
        for (auto child : currNode.first->children) {
            q.push({ child, currLevel + 1 });
        }
    }
 
    // Return the difference
    return (oddSum - evenSum);
}
 
// Driver Code
int main()
{
    // Create the N-ary Tree
    Node* root = newNode(4);
    root->children.push_back(newNode(2));
    root->children.push_back(newNode(3));
    root->children.push_back(newNode(-5));
    root->children[0]->children.push_back(newNode(-1));
    root->children[0]->children.push_back(newNode(3));
    root->children[2]->children.push_back(newNode(-2));
    root->children[2]->children.push_back(newNode(6));
 
    cout << evenOddLevelDifference(root);
 
    return 0;
}
 
 

Java




// Java program to implement
// the above approach
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
 
class GFG{
 
// Structure of a node
// of an n-ary tree
static class Node
{
    int val;
    ArrayList<Node> children;
 
    public Node(int val)
    {
        this.val = val;
        this.children = new ArrayList<Node>();
    }
};
 
static class Pair
{
    Node first;
    int second;
 
    public Pair(Node node, int val)
    {
        this.first = node;
        this.second = val;
    }
}
 
// Function to find the difference
// between of sums node values of
// odd and even levels in an N-ary tree
static int evenOddLevelDifference(Node root)
{
     
    // Store the sums of nodes at
    // even and odd levels
    int evenSum = 0, oddSum = 0;
 
    // Initialize a queue to store
    // pair of node and level
    Queue<Pair> q = new LinkedList<>();
 
    // Push the root into the
    // queue with level 1
    q.add(new Pair(root, 1));
 
    // Iterate all levels
    // of tree are traversed
    while (!q.isEmpty())
    {
         
        // Store the node at the
        // front of the queue
        Pair currNode = q.poll();
 
        // Store the current level
        int currLevel = currNode.second;
 
        // Store the current node value
        int currVal = currNode.first.val;
 
        // If current node
        // level is odd
        if (currLevel % 2 == 1)
         
            // Add to odd sum
            oddSum += currVal;
        else
         
            // Add to even sum
            evenSum += currVal;
 
        // Push all the children of current node
        // with increasing current level by 1
        for(Node child : currNode.first.children)
        {
            q.add(new Pair(child, currLevel + 1));
        }
    }
 
    // Return the difference
    return (oddSum - evenSum);
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Create the N-ary Tree
    Node root = new Node(4);
    root.children.add(new Node(2));
    root.children.add(new Node(3));
    root.children.add(new Node(-5));
    root.children.get(0).children.add(new Node(-1));
    root.children.get(0).children.add(new Node(3));
    root.children.get(2).children.add(new Node(-2));
    root.children.get(2).children.add(new Node(6));
 
    System.out.println(evenOddLevelDifference(root));
}
}
 
// This code is contributed by sanjeev2552
 
 

Python3




# Python3 program to implement
# the above approach
 
# Structure of a node
# of an n-ary tree
class Node:
     
    def __init__(self, val):
         
        self.val = val
        self.children = []
         
# Function to create a
# new tree node
def newNode(val):
 
    temp = Node(val)
     
    return temp
 
# Function to find the difference
# between of sums node values of
# odd and even levels in an N-ary tree
def evenOddLevelDifference(root):
 
    # Store the sums of nodes at
    # even and odd levels
    evenSum = 0
    oddSum = 0
  
    # Initialize a queue to store
    # pair of node and level
    q = []
  
    # Push the root into the
    # queue with level 1
    q.append([root, 1])
  
    # Iterate all levels
    # of tree are traversed
    while (len(q) != 0):
         
        # Store the node at the
        # front of the queue
        currNode = q[0]
  
        # Pop the front node
        q.pop(0)
  
        # Store the current level
        currLevel = currNode[1]
  
        # Store the current node value
        currVal = currNode[0].val
  
        # If current node
        # level is odd
        if (currLevel % 2 != 0):
  
            # Add to odd sum
            oddSum += currVal
        else:
  
            # Add to even sum
            evenSum += currVal
  
        # Push all the children of current node
        # with increasing current level by 1
        for child in currNode[0].children:
            q.append([child, currLevel + 1])
         
    # Return the difference
    return (oddSum - evenSum)
 
# Driver code
if __name__=="__main__":
     
    # Create the N-ary Tree
    root = newNode(4)
    root.children.append(newNode(2))
    root.children.append(newNode(3))
    root.children.append(newNode(-5))
    root.children[0].children.append(newNode(-1))
    root.children[0].children.append(newNode(3))
    root.children[2].children.append(newNode(-2))
    root.children[2].children.append(newNode(6))
  
    print(evenOddLevelDifference(root))
         
# This code is contributed by rutvik_56
 
 

C#




// C# program to implement
// the above approach
using System;
using System.Collections;
using System.Collections.Generic;
 
class GFG{
  
// Structure of a node
// of an n-ary tree
class Node
{
    public int val;
    public ArrayList children;
     
    public Node(int val)
    {
        this.val = val;
        this.children = new ArrayList();
    }
};
  
class Pair
{
    public Node first;
    public int second;
     
    public Pair(Node node, int val)
    {
        this.first = node;
        this.second = val;
    }
}
  
// Function to find the difference
// between of sums node values of
// odd and even levels in an N-ary tree
static int evenOddLevelDifference(Node root)
{
     
    // Store the sums of nodes at
    // even and odd levels
    int evenSum = 0, oddSum = 0;
  
    // Initialize a queue to store
    // pair of node and level
    Queue q = new Queue();
  
    // Push the root into the
    // queue with level 1
    q.Enqueue(new Pair(root, 1));
  
    // Iterate all levels
    // of tree are traversed
    while (q.Count != 0)
    {
         
        // Store the node at the
        // front of the queue
        Pair currNode = (Pair)q.Dequeue();
  
        // Store the current level
        int currLevel = currNode.second;
  
        // Store the current node value
        int currVal = currNode.first.val;
  
        // If current node
        // level is odd
        if (currLevel % 2 == 1)
          
            // Add to odd sum
            oddSum += currVal;
        else
          
            // Add to even sum
            evenSum += currVal;
  
        // Push all the children of current node
        // with increasing current level by 1
        foreach(Node child in currNode.first.children)
        {
            q.Enqueue(new Pair(child, currLevel + 1));
        }
    }
  
    // Return the difference
    return(oddSum - evenSum);
}
  
// Driver Code
public static void Main(string[] args)
{
     
    // Create the N-ary Tree
    Node root = new Node(4);
    root.children.Add(new Node(2));
    root.children.Add(new Node(3));
    root.children.Add(new Node(-5));
     
    ((Node)root.children[0]).children.Add(new Node(-1));
    ((Node)root.children[0]).children.Add(new Node(3));
    ((Node)root.children[2]).children.Add(new Node(-2));
    ((Node)root.children[2]).children.Add(new Node(6));
  
    Console.Write(evenOddLevelDifference(root));
}
}
 
// This code is contributed by pratham76
 
 

Javascript




<script>
 
    // JavaScript implementation of the above approach
     
    // Structure of a node of an n-ary tree
    // Structure of a Tree Node
    class Node
    {
        constructor(val) {
           this.children = [];
           this.val = val;
        }
    }
     
    // Function to find the difference
    // between of sums node values of
    // odd and even levels in an N-ary tree
    function evenOddLevelDifference(root)
    {
 
        // Store the sums of nodes at
        // even and odd levels
        let evenSum = 0, oddSum = 0;
 
        // Initialize a queue to store
        // pair of node and level
        let q = [];
 
        // Push the root into the
        // queue with level 1
        q.push([root, 1]);
 
        // Iterate all levels
        // of tree are traversed
        while (q.length != 0)
        {
 
            // Store the node at the
            // front of the queue
            let currNode = q[0];
            q.shift();
 
            // Store the current level
            let currLevel = currNode[1];
 
            // Store the current node value
            let currVal = currNode[0].val;
 
            // If current node
            // level is odd
            if (currLevel % 2 == 1)
 
                // Add to odd sum
                oddSum += currVal;
            else
 
                // Add to even sum
                evenSum += currVal;
 
            // Push all the children of current node
            // with increasing current level by 1
            for(let child = 0; child < (currNode[0].children).length;
            child++)
            {
                q.push([currNode[0].children[child], currLevel + 1]);
            }
        }
 
        // Return the difference
        return(oddSum - evenSum);
    }
     
    // Create the N-ary Tree
    let root = new Node(4);
    root.children.push(new Node(2));
    root.children.push(new Node(3));
    root.children.push(new Node(-5));
      
    (root.children[0]).children.push(new Node(-1));
    (root.children[0]).children.push(new Node(3));
    (root.children[2]).children.push(new Node(-2));
    (root.children[2]).children.push(new Node(6));
   
    document.write(evenOddLevelDifference(root));
     
</script>
 
 
Output: 
10

 

Time Complexity: O(N)
Auxiliary Space: O(N)

 



Next Article
Difference between sum of odd and even frequent elements in an Array

M

muskan_garg
Improve
Article Tags :
  • DSA
  • Queue
  • Searching
  • Tree
  • BFS
  • n-ary-tree
  • Tree Traversals
Practice Tags :
  • BFS
  • Queue
  • Searching
  • Tree

Similar Reads

  • Difference between sums of odd level and even level nodes of a Binary Tree
    Given a Binary Tree, the task is to find the difference between the sum of nodes at the odd level and the sum of nodes at the even level. Examples: Input: Output: -4Explanation: sum at odd levels - sum at even levels = (1) - (2 + 3) = 1 - 5 = -4Input: Output: 60Explanation: Sum at odd levels - Sum a
    14 min read
  • Difference between sum of even and odd valued nodes in a Binary Tree
    Given a binary tree, the task is to find the absolute difference between the even valued and the odd valued nodes in a binary tree. Examples: Input: 5 / \ 2 6 / \ \ 1 4 8 / / \ 3 7 9 Output: 5 Explanation: Sum of the odd value nodes is: 5 + 1 + 3 + 7 + 9 = 25 Sum of the even value nodes is: 2 + 6 +
    10 min read
  • Difference between sum of odd and even frequent elements in an Array
    Given an array arr[] of integers, the task is to find the absolute difference between the sum of all odd frequent array elements and the sum of all even frequent array elements. Examples: Input: arr[] = {1, 5, 5, 2, 4, 3, 3} Output: 9 Explanation: The even frequent elements are 5 and 3 (both occurri
    12 min read
  • Difference between odd level and even level leaf sum in given Binary Tree
    Given a Binary Tree, the task is to find the difference of the sum of leaf nodes at the odd level and even level of the given tree. Examples: Input: Output: -12Explanation: Following are the operations performed to get the result.odd_level_sum = 0, even_level_sum = 0Level 1: No leaf node, so odd_lev
    13 min read
  • Difference between sums of odd position and even position nodes for each level of a Binary Tree
    Given a Binary Tree, the task is to find the absolute difference between the sums of odd and even positioned nodes. A node is said to be odd and even positioned if its position in the current level is odd and even respectively. Note that the first element of each row is considered as odd positioned.
    8 min read
  • Difference between sum of K maximum even and odd array elements
    Given an array arr[] and a number K, the task is to find the absolute difference of the sum of K maximum even and odd array elements.Note: At least K even and odd elements are present in the array respectively. Examples: Input arr[] = {1, 2, 3, 4, 5, 6}, K = 2Output: 2Explanation:The 2 maximum even
    8 min read
  • Maximum absolute difference between any two level sum in a N-ary Tree
    Given an N-ary Tree having N nodes with positive and negative values and (N - 1) edges, the task is to find the maximum absolute difference of level sum in it. Examples: Input: N = 8, Edges[][2] = {{0, 1}, {0, 2}, {0, 3}, {1, 4}, {1, 5}, {3, 6}, {6, 7}}, Value[] = {4,2, 3, -5,-1, 3, -2, 6}, Below is
    9 min read
  • Maximize difference between sum of even and odd-indexed elements of a subsequence
    Given an array arr[] consisting of N positive integers, the task is to find the maximum possible difference between the sum of even and odd-indexed elements of a subsequence from the given array. Examples: Input: arr[] = { 3, 2, 1, 4, 5, 2, 1, 7, 8, 9 } Output: 15 Explanation: Considering the subseq
    7 min read
  • Calculate sum of all nodes present in a level for each level of a Tree
    Given a Generic Tree consisting of N nodes (rooted at 0) where each node is associated with a value, the task for each level of the Tree is to find the sum of all node values present at that level of the tree. Examples: Input: node_number = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, node_values = { 2, 3, 4,
    14 min read
  • Minimum difference between any two weighted nodes in Sum Tree of the given Tree
    Given a tree of N nodes, the task is to convert the given tree to its Sum Tree(including its own weight) and find the minimum difference between any two node's weight of the sum tree. Note: The N nodes of the given tree are given in the form of top to bottom with N-1 line where each line describes t
    11 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences