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 odd level and even level leaf sum in given Binary Tree
Next article icon

Difference between sum of even and odd valued nodes in a Binary Tree

Last Updated : 21 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 + 4 + 8 = 20  Absolute difference = (25 – 20) = 5.  Input:       4     /   \    1     4  /  \     \   7    2     6 Output: 8

Approach: 
Follow the steps below to solve the problem:

  • Traverse each node in the tree and check if the value at that node is odd or even.
  • Update oddSum and evenSum accordingly after visiting each node.
  • After complete traversal of the tree, print the absolute difference between oddSum and evenSum.

Below is the implementation of the above approach:

C++




// C++ implementation of
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
int oddsum = 0;
int evensum = 0;
int ans = 0;
 
struct node {
    int data;
    struct node* left;
    struct node* right;
};
 
struct node* newnode(int data)
{
    node* temp = new node();
    temp->data = data;
    temp->left = temp->right = NULL;
    return temp;
}
 
// Function calculate the sum of
// odd and even value node
void OddEvenDifference(struct node*
                           root)
{
    // If root is NULL
    if (root == NULL) {
        return;
    }
    else {
        // Check if current root
        // is odd or even
        if (root->data % 2 == 0) {
            evensum += root->data;
        }
        else {
            oddsum += root->data;
        }
        // Call on the left subtree
        OddEvenDifference(root->left);
 
        // Call on the right subtree
        OddEvenDifference(root->right);
    }
}
 
// Driver Code
int main()
{
    node* root = newnode(5);
    root->left = newnode(2);
    root->right = newnode(6);
    root->left->left = newnode(1);
    root->left->right = newnode(4);
    root->left->right->left
        = newnode(3);
    root->right->right = newnode(8);
    root->right->right->right
        = newnode(9);
    root->right->right->left
        = newnode(7);
 
    OddEvenDifference(root);
 
    cout << abs(oddsum - evensum)
         << endl;
}
 
 

Java




// Java implementation of
// the above approach
class GFG{
 
static int oddsum = 0;
static int evensum = 0;
static int ans = 0;
 
static class node
{
    int data;
    node left;
    node right;
};
 
static node newnode(int data)
{
    node temp = new node();
    temp.data = data;
    temp.left = temp.right = null;
    return temp;
}
 
// Function calculate the sum of
// odd and even value node
static void OddEvenDifference(node root)
{
     
    // If root is null
    if (root == null)
    {
        return;
    }
    else
    {
         
        // Check if current root
        // is odd or even
        if (root.data % 2 == 0)
        {
            evensum += root.data;
        }
        else
        {
            oddsum += root.data;
        }
         
        // Call on the left subtree
        OddEvenDifference(root.left);
 
        // Call on the right subtree
        OddEvenDifference(root.right);
    }
}
 
// Driver Code
public static void main(String[] args)
{
    node root = newnode(5);
    root.left = newnode(2);
    root.right = newnode(6);
    root.left.left = newnode(1);
    root.left.right = newnode(4);
    root.left.right.left = newnode(3);
    root.right.right = newnode(8);
    root.right.right.right = newnode(9);
    root.right.right.left = newnode(7);
 
    OddEvenDifference(root);
 
    System.out.print(Math.abs(
        oddsum - evensum) + "\n");
}
}
 
// This code is contributed by amal kumar choubey
 
 

Python3




# Python3 implementation of
# the above approach
oddsum = 0
evensum = 0
 
class Node:
     
    def __init__(self, data):
         
        self.left = None
        self.right = None
        self.data = data
         
def newnode(data):
 
    temp = Node(data)
     
    return temp
 
# Function calculate the sum of
# odd and even value node
def OddEvenDifference(root):
     
    global evensum, oddsum
     
    # If root is NULL
    if (root == None):
        return
     
    else:
         
        # Check if current root
        # is odd or even
        if (root.data % 2 == 0):
            evensum += root.data
        else:
            oddsum += root.data
         
        # Call on the left subtree
        OddEvenDifference(root.left)
  
        # Call on the right subtree
        OddEvenDifference(root.right)
     
# Driver code
if __name__=="__main__":
     
    root = newnode(5)
    root.left = newnode(2)
    root.right = newnode(6)
    root.left.left = newnode(1)
    root.left.right = newnode(4)
    root.left.right.left= newnode(3)
    root.right.right = newnode(8)
    root.right.right.right= newnode(9)
    root.right.right.left= newnode(7)
  
    OddEvenDifference(root)
     
    print(abs(oddsum - evensum))
     
# This code is contributed by rutvik_56
 
 

C#




// C# implementation of
// the above approach
using System;
 
class GFG{
 
static int oddsum = 0;
static int evensum = 0;
//static int ans = 0;
 
class node
{
    public int data;
    public node left;
    public node right;
};
 
static node newnode(int data)
{
    node temp = new node();
    temp.data = data;
    temp.left = temp.right = null;
    return temp;
}
 
// Function calculate the sum of
// odd and even value node
static void OddEvenDifference(node root)
{
     
    // If root is null
    if (root == null)
    {
        return;
    }
    else
    {
         
        // Check if current root
        // is odd or even
        if (root.data % 2 == 0)
        {
            evensum += root.data;
        }
        else
        {
            oddsum += root.data;
        }
         
        // Call on the left subtree
        OddEvenDifference(root.left);
 
        // Call on the right subtree
        OddEvenDifference(root.right);
    }
}
 
// Driver Code
public static void Main(String[] args)
{
    node root = newnode(5);
    root.left = newnode(2);
    root.right = newnode(6);
    root.left.left = newnode(1);
    root.left.right = newnode(4);
    root.left.right.left = newnode(3);
    root.right.right = newnode(8);
    root.right.right.right = newnode(9);
    root.right.right.left = newnode(7);
 
    OddEvenDifference(root);
 
    Console.Write(Math.Abs(
        oddsum - evensum) + "\n");
}
}
 
// This code is contributed by amal kumar choubey
 
 

Javascript




<script>
    // Javascript implementation of the above approach
     
    let oddsum = 0;
    let evensum = 0;
    let ans = 0;
 
    class node
    {
        constructor(data) {
           this.data = data;
           this.left = this.right = null;
        }
    }
     
    function newnode(data)
    {
        let temp = new node(data);
        return temp;
    }
 
    // Function calculate the sum of
    // odd and even value node
    function OddEvenDifference(root)
    {
 
        // If root is null
        if (root == null)
        {
            return;
        }
        else
        {
 
            // Check if current root
            // is odd or even
            if (root.data % 2 == 0)
            {
                evensum += root.data;
            }
            else
            {
                oddsum += root.data;
            }
 
            // Call on the left subtree
            OddEvenDifference(root.left);
 
            // Call on the right subtree
            OddEvenDifference(root.right);
        }
    }
     
    let root = newnode(5);
    root.left = newnode(2);
    root.right = newnode(6);
    root.left.left = newnode(1);
    root.left.right = newnode(4);
    root.left.right.left = newnode(3);
    root.right.right = newnode(8);
    root.right.right.right = newnode(9);
    root.right.right.left = newnode(7);
  
    OddEvenDifference(root);
  
    document.write(Math.abs(oddsum - evensum) + "</br>");
 
</script>
 
 
Output: 
5

 

Time Complexity: O(N)  where N is the number of nodes in given Binary Tree, as it does a simple traversal of the tree.
Auxiliary Space: O(h) where h is the height of given Binary Tree due to Recursion.
 
Another Approach (Iterative):
We can solve this problem by level order traversal using queue. 

Below is the implementation of above approach:

C++




// C++ Program for the above approach
#include<bits/stdc++.h>
using namespace std;
 
// structure of node
struct Node{
    int data;
    struct Node* left = NULL;
    struct Node* right = NULL;
    Node(int data){
        this->data = data;
        this->left = this->right = NULL;
    }
};
 
// Utility function to create node
Node* newnode(int data){
    return new Node(data);
}
 
// function to find the absolute difference
int OddEvenDifference(Node* root){
    int oddSum = 0;
    int evenSum = 0;
    queue<Node*> q;
    q.push(root);
    while(!q.empty()){
        Node* front_node = q.front();
        q.pop();
        if(front_node->data % 2 == 0) evenSum += front_node->data;
        else oddSum += front_node->data;
         
        if(front_node->left != NULL) q.push(front_node->left);
        if(front_node->right != NULL) q.push(front_node->right);
    }
    return abs(oddSum - evenSum);
}
 
// Driver code
int main(){
    Node* root = newnode(5);
    root->left = newnode(2);
    root->right = newnode(6);
    root->left->left = newnode(1);
    root->left->right = newnode(4);
    root->left->right->left = newnode(3);
    root->right->right = newnode(8);
    root->right->right->right = newnode(9);
    root->right->right->left = newnode(7);
  
    cout<<OddEvenDifference(root);
    return 0;
}
// This code is contributed by Kirti Agarwal(kirtiagarwal23121999)
 
 

Python3




# Python Program for the above approach
import queue
 
# structure of node
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
# function to find the absolute difference
def OddEvenDifference(root):
    oddSum = 0
    evenSum = 0
    # create a queue
    q = queue.Queue()
    q.put(root)
    while(not q.empty()):
        front_node = q.get() # get the front node from the queue
        if(front_node.data % 2 == 0): # if the data of the front node is even
            evenSum += front_node.data # add it to the even sum
        else:
            oddSum += front_node.data # otherwise, add it to the odd sum
         
        if(front_node.left is not None): # if the front node has a left child
            q.put(front_node.left) # add it to the queue
        if(front_node.right is not None): # if the front node has a right child
            q.put(front_node.right) # add it to the queue
    return abs(oddSum - evenSum) # return the absolute difference between the odd and even sums
 
# Driver code
if __name__ == '__main__':
    root = Node(5)
    root.left = Node(2)
    root.right = Node(6)
    root.left.left = Node(1)
    root.left.right = Node(4)
    root.left.right.left = Node(3)
    root.right.right = Node(8)
    root.right.right.right = Node(9)
    root.right.right.left = Node(7)
     
   # call the OddEvenDifference function and print the result
    print(OddEvenDifference(root))
 
 

Java




// Java Program for the above approach
import java.util.*;
 
// structure of node
class Node{
    int data;
    Node left;
    Node right;
    Node(int data){
        this.data = data;
        this.left = null;
        this.right = null;
    }
};
 
// Driver code
class Main {
    // function to find the absolute difference
    static int OddEvenDifference(Node root){
        int oddSum = 0;
        int evenSum = 0;
        Queue<Node> q = new LinkedList<Node>();
        q.add(root);
        while(!q.isEmpty()){
            Node front_node = q.poll();
            if(front_node.data % 2 == 0) evenSum += front_node.data;
            else oddSum += front_node.data;
 
            if(front_node.left != null) q.add(front_node.left);
            if(front_node.right != null) q.add(front_node.right);
        }
        return Math.abs(oddSum - evenSum);
    }
 
    public static void main(String[] args) {
        Node root = new Node(5);
        root.left = new Node(2);
        root.right = new Node(6);
        root.left.left = new Node(1);
        root.left.right = new Node(4);
        root.left.right.left = new Node(3);
        root.right.right = new Node(8);
        root.right.right.right = new Node(9);
        root.right.right.left = new Node(7);
 
        System.out.println(OddEvenDifference(root));
    }
}
 
 

Javascript




// JavaScript program for the above approach
// class of tree node
class Node{
    constructor(data){
        this.data = data;
        this.left = null;
        this.right = null;
    }
}
 
// utility function to create node
function newnode(data){
    return new Node(data);
}
 
// function to find the absolute difference
function oddEvenDifference(root){
    let oddSum = 0;
    let evenSum = 0;
    let q = [];
    q.push(root);
    while(q.length > 0){
        let front_node = q.shift();
        if(front_node.data % 2 == 0) evenSum += front_node.data;
        else oddSum += front_node.data;
         
        if(front_node.left) q.push(front_node.left);
        if(front_node.right) q.push(front_node.right);
    }
    return Math.abs(oddSum - evenSum);
}
 
// driver code
let root = newnode(5);
root.left = newnode(2);
root.right = newnode(6);
root.left.left = newnode(1);
root.left.right = newnode(4);
root.left.right.left = newnode(3);
root.right.right = newnode(8);
root.right.right.right = newnode(9);
root.right.right.left = newnode(7);
 
console.log(oddEvenDifference(root));
 
 

C#




// C# Program for the above approach
using System;
using System.Collections.Generic;
 
// structure of node
public class Node {
    public int data;
    public Node left = null;
    public Node right = null;
    public Node(int data)
    {
        this.data = data;
        this.left = this.right = null;
    }
}
 
class MainClass {
    // Utility function to create node
    static Node newnode(int data) { return new Node(data); }
    // function to find the absolute difference
    static int OddEvenDifference(Node root)
    {
        int oddSum = 0;
        int evenSum = 0;
        Queue<Node> q = new Queue<Node>();
        q.Enqueue(root);
        while (q.Count > 0) {
            Node front_node = q.Peek();
            q.Dequeue();
            if (front_node.data % 2 == 0)
                evenSum += front_node.data;
            else
                oddSum += front_node.data;
 
            if (front_node.left != null)
                q.Enqueue(front_node.left);
            if (front_node.right != null)
                q.Enqueue(front_node.right);
        }
        return Math.Abs(oddSum - evenSum);
    }
 
    // Driver code
    static void Main(string[] args)
    {
        Node root = newnode(5);
        root.left = newnode(2);
        root.right = newnode(6);
        root.left.left = newnode(1);
        root.left.right = newnode(4);
        root.left.right.left = newnode(3);
        root.right.right = newnode(8);
        root.right.right.right = newnode(9);
        root.right.right.left = newnode(7);
 
        Console.WriteLine(OddEvenDifference(root));
    }
}
// This code is contributed by user_dtewbxkn77n
 
 
Output
5


Next Article
Difference between odd level and even level leaf sum in given Binary Tree
author
sunilkannur98
Improve
Article Tags :
  • Data Structures
  • DSA
  • Recursion
  • Tree
  • Binary Tree
  • Data Structures-Tree Traversals
  • interview-preparation
Practice Tags :
  • Data Structures
  • Recursion
  • 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 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
  • Create loops of even and odd values in a binary tree
    Given a binary tree with the node structure containing a data part, left and right pointers, and an arbitrary pointer(abtr). The node's value can be any positive integer. The problem is to create odd and even loops in a binary tree. An odd loop is a loop that connects all the nodes having odd number
    10 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
  • Sum of cousins of a given node in a Binary Tree
    Given a binary tree and data value of a node. The task is to find the sum of cousin nodes of given node. If given node has no cousins then return -1. Note: It is given that all nodes have distinct values and the given node exists in the tree. Examples: Input: 1 / \ 3 7 / \ / \ 6 5 4 13 / / \ 10 17 1
    11 min read
  • Difference between Binary tree and B-tree
    B-Tree : B-Tree is known as a self-balancing tree as its nodes are sorted in the inorder traversal. Unlike the binary trees, in B-tree, a node can have more than two children. B-tree has a height of logM N (Where ‘M’ is the order of tree and N is the number of nodes). And the height is adjusts autom
    7 min read
  • Sum of decimal equivalents of binary node values in each level of a Binary Tree
    Given a Binary Tree consisting of nodes with values 0 and 1 only, the task is to find the total sum of the decimal equivalents of the binary numbers formed by connecting nodes at the same level from left to right, on each level. Examples: Input: Below is the given Tree: 0 / \ 1 0 / \ / \ 0 1 1 1Outp
    15 min read
  • Maximum absolute difference between any two level sum in a Binary Tree
    Given a Binary Tree having positive and negative nodes, the task is to find the maximum absolute difference of level sum in it. Examples: Input: 4 / \ 2 -5 / \ / \ -1 3 -2 6 Output: 9 Explanation: Sum of all nodes of 0 level is 4 Sum of all nodes of 1 level is -3 Sum of all nodes of 2 level is 6 Hen
    10 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