Related Articles

Related Articles

Difference between sums of odd level and even level nodes in an N-ary Tree
  • Last Updated : 01 Dec, 2020

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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


Output: 

10

 

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

 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :