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:
Print odd positioned nodes of even levels in level order of the given binary tree
Next article icon

Difference between sums of odd position and even position nodes for each level of a Binary Tree

Last Updated : 17 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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.
Examples: 
 

Input:       5     /   \    2     6  /  \     \   1    4     8     /     / \     3     7   9 Output: 11 Level     oddPositionNodeSum  evenPositionNodeSum 0             5                  0 1             2                  6 2             9                  4 3             12                 7 Difference = |(5 + 2 + 9 + 12) - (0 + 6 + 4 + 7)| = |28 - 17| = 11  Input:       5     /   \    2     3 Output: 4

 

Approach: To find the sum of nodes at even and odd positions level by level, use level order traversal. While traversing the tree level by level mark flag oddPosition as true for the first element of each row and switch it for each next element of the same row. And in case if oddPosition flag is true add the node data into oddPositionNodeSum else add node data to evenPositionNodeSum. After completion of tree traversal find the absolute value of their differences at the end of the tree traversal.
Below is the implementation of the above approach: 
 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
struct Node {
    int data;
    Node *left, *right;
};
 
// Iterative method to perform level
// order traversal line by line
int nodeSumDiff(Node* root)
{
 
    // Base Case
    if (root == NULL)
        return 0;
 
    int evenPositionNodeSum = 0;
    int oddPositionNodeSum = 0;
 
    // Create an empty queue for level
    // order traversal
    queue<Node*> q;
 
    // Enqueue root element
    q.push(root);
 
    while (1) {
 
        // nodeCount (queue size) indicates
        // number of nodes in the current level
        int nodeCount = q.size();
        if (nodeCount == 0)
            break;
 
        // Mark 1st node as even positioned
        bool oddPosition = true;
 
        // Dequeue all the nodes of current level
        // and Enqueue all the nodes of next level
        while (nodeCount > 0) {
            Node* node = q.front();
 
            // Depending upon node position
            // add value to their respective sum
            if (oddPosition)
                oddPositionNodeSum += node->data;
            else
                evenPositionNodeSum += node->data;
 
            q.pop();
            if (node->left != NULL)
                q.push(node->left);
            if (node->right != NULL)
                q.push(node->right);
            nodeCount--;
 
            // Switch the even position flag
            oddPosition = !oddPosition;
        }
    }
 
    // Return the absolute difference
    return abs(oddPositionNodeSum - evenPositionNodeSum);
}
 
// Utility method to create a node
struct Node* newNode(int data)
{
    struct Node* node = new Node;
    node->data = data;
    node->left = node->right = NULL;
    return (node);
}
 
// Driver code
int main()
{
    struct Node* root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(3);
    root->left->left = newNode(4);
    root->left->right = newNode(5);
    root->right->left = newNode(6);
    root->right->right = newNode(7);
    root->left->right->left = newNode(8);
    root->left->right->right = newNode(9);
    root->left->right->right->right = newNode(10);
 
    cout << nodeSumDiff(root);
 
    return 0;
}
 
 

Java




// Java implementation of the approach
import java.util.*;
 
class GFG
{
 
    static class Node
    {
        int data;
        Node left, right;
    };
 
    // Iterative method to perform level
    // order traversal line by line
    static int nodeSumDiff(Node root)
    {
 
        // Base Case
        if (root == null)
            return 0;
 
        int evenPositionNodeSum = 0;
        int oddPositionNodeSum = 0;
 
        // Create an empty queue for level
        // order traversal
        Queue<Node> q = new LinkedList<>();
 
        // Enqueue root element
        q.add(root);
 
        while (1 == 1)
        {
 
            // nodeCount (queue size) indicates
            // number of nodes in the current level
            int nodeCount = q.size();
            if (nodeCount == 0)
                break;
 
            // Mark 1st node as even positioned
            boolean oddPosition = true;
 
            // Dequeue all the nodes of current level
            // and Enqueue all the nodes of next level
            while (nodeCount > 0)
            {
                Node node = q.peek();
 
                // Depending upon node position
                // add value to their respective sum
                if (oddPosition)
                    oddPositionNodeSum += node.data;
                else
                    evenPositionNodeSum += node.data;
 
                q.remove();
                if (node.left != null)
                    q.add(node.left);
                if (node.right != null)
                    q.add(node.right);
                nodeCount--;
 
                // Switch the even position flag
                oddPosition = !oddPosition;
            }
        }
 
        // Return the absolute difference
        return Math.abs(oddPositionNodeSum - evenPositionNodeSum);
    }
 
    // Utility method to create a node
    static Node newNode(int data)
    {
        Node node = new Node();
        node.data = data;
        node.left = node.right = null;
        return (node);
    }
 
    // Driver code
    public static void main(String[] args)
    {
        Node root = newNode(1);
        root.left = newNode(2);
        root.right = newNode(3);
        root.left.left = newNode(4);
        root.left.right = newNode(5);
        root.right.left = newNode(6);
        root.right.right = newNode(7);
        root.left.right.left = newNode(8);
        root.left.right.right = newNode(9);
        root.left.right.right.right = newNode(10);
 
        System.out.print(nodeSumDiff(root));
 
    }
}
 
// This code is contributed by PrinciRaj1992
 
 

Python




# Python implementation of the approach
 
# Node of a linked list
class Node:
    def __init__(self, data = None,
                left = None, right = None):
        self.left = left
        self.right = right
        self.data = data
 
# Iterative method to perform level
# order traversal line by line
def nodeSumDiff( root):
 
    # Base Case
    if (root == None):
        return 0
 
    evenPositionNodeSum = 0
    oddPositionNodeSum = 0
 
    # Create an empty queue for level
    # order traversal
    q = []
 
    # Enqueue root element
    q.append(root)
 
    while (True):
 
        # nodeCount (queue size) indicates
        # number of nodes in the current level
        nodeCount = len(q)
        if (nodeCount == 0):
            break
 
        # Mark 1st node as even positioned
        oddPosition = True
 
        # Dequeue all the nodes of current level
        # and Enqueue all the nodes of next level
        while (nodeCount > 0):
            node = q[0]
 
            # Depending upon node position
            # add value to their respective sum
            if (oddPosition):
                oddPositionNodeSum += node.data
            else:
                evenPositionNodeSum += node.data
 
            q.pop(0)
            if (node.left != None):
                q.append(node.left)
            if (node.right != None):
                q.append(node.right)
            nodeCount = nodeCount - 1
 
            # Switch the even position flag
            oddPosition = not oddPosition
         
    # Return the absolute difference
    return abs(oddPositionNodeSum - evenPositionNodeSum)
 
# Utility method to create a node
def newNode(data):
    node = Node()
    node.data = data
    node.left = node.right = None
    return (node)
 
# Driver code
root = newNode(1)
root.left = newNode(2)
root.right = newNode(3)
root.left.left = newNode(4)
root.left.right = newNode(5)
root.right.left = newNode(6)
root.right.right = newNode(7)
root.left.right.left = newNode(8)
root.left.right.right = newNode(9)
root.left.right.right.right = newNode(10)
 
print(nodeSumDiff(root))
 
# This code is contributed by Arnab Kundu
 
 

C#




// C# implementation of the approach
using System;
using System.Collections.Generic;
 
class GFG
{
 
    public class Node
    {
        public int data;
        public Node left, right;
    };
 
    // Iterative method to perform level
    // order traversal line by line
    static int nodeSumDiff(Node root)
    {
 
        // Base Case
        if (root == null)
            return 0;
 
        int evenPositionNodeSum = 0;
        int oddPositionNodeSum = 0;
 
        // Create an empty queue for level
        // order traversal
        Queue<Node> q = new Queue<Node>();
 
        // Enqueue root element
        q.Enqueue(root);
 
        while (1 == 1)
        {
 
            // nodeCount (queue size) indicates
            // number of nodes in the current level
            int nodeCount = q.Count;
            if (nodeCount == 0)
                break;
 
            // Mark 1st node as even positioned
            bool oddPosition = true;
 
            // Dequeue all the nodes of current level
            // and Enqueue all the nodes of next level
            while (nodeCount > 0)
            {
                Node node = q.Peek();
 
                // Depending upon node position
                // add value to their respective sum
                if (oddPosition)
                    oddPositionNodeSum += node.data;
                else
                    evenPositionNodeSum += node.data;
 
                q.Dequeue();
                if (node.left != null)
                    q.Enqueue(node.left);
                if (node.right != null)
                    q.Enqueue(node.right);
                nodeCount--;
 
                // Switch the even position flag
                oddPosition = !oddPosition;
            }
        }
 
        // Return the absolute difference
        return Math.Abs(oddPositionNodeSum - evenPositionNodeSum);
    }
 
    // Utility method to create a node
    static Node newNode(int data)
    {
        Node node = new Node();
        node.data = data;
        node.left = node.right = null;
        return (node);
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        Node root = newNode(1);
        root.left = newNode(2);
        root.right = newNode(3);
        root.left.left = newNode(4);
        root.left.right = newNode(5);
        root.right.left = newNode(6);
        root.right.right = newNode(7);
        root.left.right.left = newNode(8);
        root.left.right.right = newNode(9);
        root.left.right.right.right = newNode(10);
 
        Console.Write(nodeSumDiff(root));
    }
}
 
// This code is contributed by Rajput-Ji
 
 

Javascript




<script>
 
    // JavaScript implementation of the approach
     
    class Node
    {
        constructor(data) {
           this.left = null;
           this.right = null;
           this.data = data;
        }
    }
     
    // Iterative method to perform level
    // order traversal line by line
    function nodeSumDiff(root)
    {
   
        // Base Case
        if (root == null)
            return 0;
   
        let evenPositionNodeSum = 0;
        let oddPositionNodeSum = 0;
   
        // Create an empty queue for level
        // order traversal
        let q = [];
   
        // Enqueue root element
        q.push(root);
   
        while (1 == 1)
        {
   
            // nodeCount (queue size) indicates
            // number of nodes in the current level
            let nodeCount = q.length;
            if (nodeCount == 0)
                break;
   
            // Mark 1st node as even positioned
            let oddPosition = true;
   
            // Dequeue all the nodes of current level
            // and Enqueue all the nodes of next level
            while (nodeCount > 0)
            {
                let node = q[0];
   
                // Depending upon node position
                // add value to their respective sum
                if (oddPosition)
                    oddPositionNodeSum += node.data;
                else
                    evenPositionNodeSum += node.data;
   
                q.shift();
                if (node.left != null)
                    q.push(node.left);
                if (node.right != null)
                    q.push(node.right);
                nodeCount--;
   
                // Switch the even position flag
                oddPosition = !oddPosition;
            }
        }
   
        // Return the absolute difference
        return Math.abs(oddPositionNodeSum - evenPositionNodeSum);
    }
   
    // Utility method to create a node
    function newNode(data)
    {
        let node = new Node(data);
        return (node);
    }
     
    let root = newNode(1);
    root.left = newNode(2);
    root.right = newNode(3);
    root.left.left = newNode(4);
    root.left.right = newNode(5);
    root.right.left = newNode(6);
    root.right.right = newNode(7);
    root.left.right.left = newNode(8);
    root.left.right.right = newNode(9);
    root.left.right.right.right = newNode(10);
 
    document.write(nodeSumDiff(root));
     
</script>
 
 
Output: 
7

 

Time Complexity: O(N) where n is the number of nodes in the binary tree.
Auxiliary Space: O(N) where n is the number of nodes in the binary tree.



Next Article
Print odd positioned nodes of even levels in level order of the given binary tree

S

Shivam.Pradhan
Improve
Article Tags :
  • DSA
  • Tree
  • Binary Tree
  • tree-level-order
Practice Tags :
  • 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 sums of odd level and even level nodes in an N-ary Tree
    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 6Output: 10Explanation:Sum of nodes at even levels = 2 + 3 + (-5) = 0Sum of nodes at odd levels = 4 + (-1)
    9 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
  • Print odd positioned nodes of even levels in level order of the given binary tree
    Given a binary tree, the task is to print the odd positioned nodes of even levels in the level order traversal of the tree. The root is considered at level 0, and the leftmost node of any level is considered as a node at position 0.Example: Input: 1 / \ 2 3 / \ / \ 4 5 6 7 / \ 8 9 / \ 10 11 Output:
    8 min read
  • Print even positioned nodes of odd levels in level order of the given binary tree
    Given a binary tree, the task is to print the even positioned nodes of odd levels in the level order traversal of the tree. The root is considered at level 0, and the leftmost node of any level is considered as a node at position 0.Example: Input: 1 / \ 2 3 / \ / \ 4 5 6 7 / \ 8 9 / \ 10 11 Output:
    8 min read
  • Print odd positioned nodes of odd levels in level order of the given binary tree
    Given a binary tree, the task is to print the odd positioned nodes of odd levels in the level order traversal of the tree. The root is considered at level 0, and the leftmost node of any level is considered as a node at position 0.Example: Input: 1 / \ 2 3 / \ / \ 4 5 6 7 / \ 8 9 / \ 10 11 Output: 3
    8 min read
  • Sum of Bitwise AND of the sum of all leaf and non-leaf nodes for each level of a Binary Tree
    Given a Binary Tree consisting of N nodes, the task is to find the sum of Bitwise AND of the sum of all leaf nodes and the sum of all non-leaf nodes for each level in the given Tree. Examples: Input: Below is the given tree: 5 / \ 3 9 / \ 6 4 \ 7Output: 5Explanation: For Level 1: leaf node sum = 0,
    10 min read
  • Append odd position nodes in reverse at the end of even positioned nodes in a Linked List
    Given a linked list. The task is to segregate its even and odd position nodes in such a way that odd position nodes appear before even positioned nodes all the even positioned nodes must be in reverse order. Examples: Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULL Output : 1 -> 3 -
    11 min read
  • Print even positioned nodes of even levels in level order of the given binary tree
    Given a binary tree, print even positioned nodes of even level in level order traversal. The root is considered at level 0, and the left most node of any level is considered as a node at position 0. Examples: Input: 1 / \ 2 3 / \ \ 4 5 6 / \ 7 8 / \ 9 10 Output: 1 4 6 9 Input: 2 / \ 4 15 / / 45 17 O
    8 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