Open In App

Difference between odd level and even level leaf sum in given Binary Tree

Improve
Improve
Like Article
Like
Save
Share
Report

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: -12
Explanation: Following are the operations performed to get the result.
odd_level_sum = 0, even_level_sum = 0
Level 1: No leaf node, so odd_level_sum = 0
Level 2: No leaf node, so even_level_sum = 0
Level 3: One leaf node: 6, so odd_level_sum = 0 + 6 = 6 
Level 4: Three leaf nodes: 9, 10, 11, so even_level_sum = 0 + 9 + 10 + 11 = 30
Level 5: One leaf node: 12, so odd_level_sum = 6 + 12 = 18
Therefore, result = odd_level_sum – even_level_sum = 18 – 30 = -12

Input:

Output: -12

Approach: The given problem can be solved by using the Level Order Traversal. Follow the steps below to solve the given problem.

  • Create a queue q, to store the node. Also, create two variables odd_level_sum and even_level_sum to store the sum of leaf nodes at the odd and even levels of the tree respectively. The other variable level keeps track of the level in the traversal.
  • Perform the level order traversal from the root node and store each node in the queue, and also check the current node for the leaf node. If it’s a leaf node then add its value in the odd_level_sum or even_level_sum by checking the level.
  • After completing the above steps, print the difference between odd_level_sum and even_level_sum.

Below is the implementation of the above approach: 

C++




// C++ program for above approach
#include <bits/stdc++.h>
using namespace std;
 
// A tree node structure
struct Node {
    int data;
    Node *left, *right;
};
 
// Utility function to create
// a new Binary Tree node
Node* newNode(int data)
{
    Node* temp = new Node;
    temp->data = data;
    temp->left = temp->right = NULL;
    return temp;
}
 
// Function to print the difference
void printDifference(Node* root)
{
    if (root == NULL) {
        cout << "No nodes present\n";
        return;
    }
 
    int odd_level_sum = 0,
        even_level_sum = 0,
        level = 1;
 
    // queue to hold tree node with level
    queue<struct Node*> q;
 
    // Root node is at level 1 so level=1
    q.push(root);
 
    // Do level Order Traversal of tree
    while (!q.empty()) {
        int n = q.size();
        while (n--) {
            Node* temp = q.front();
            q.pop();
            if (temp->left == NULL
                && temp->right == NULL) {
                if (level & 1) {
                    odd_level_sum += temp->data;
                }
                else {
                    even_level_sum += temp->data;
                }
                continue;
            }
            if (temp->left) {
                q.push(temp->left);
            }
            if (temp->right) {
                q.push(temp->right);
            }
        }
        level++;
    }
    cout << odd_level_sum - even_level_sum;
}
 
// Driver Code
int main()
{
    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->left->right = newNode(8);
    root->left->right->right = newNode(9);
    root->right->right->left = newNode(10);
    root->right->right->right = newNode(11);
    root->left->left->right->right = newNode(12);
 
    printDifference(root);
 
    return 0;
}


Java




// Java program for above approach
import java.util.LinkedList;
import java.util.Queue;
 
class GFG {
 
  // A tree node structure
  static class Node {
    int data;
    Node left;
    Node right;
 
    public Node(int data) {
      this.data = data;
      this.left = null;
      this.right = null;
    }
  };
 
  // Utility function to create
  // a new Binary Tree node
  static Node Node(int data) {
    Node temp = new Node(0);
    temp.data = data;
    temp.left = temp.right = null;
    return temp;
  }
 
  // Function to print the difference
  static void printDifference(Node root) {
    if (root == null) {
      System.out.println("No nodes present");
      return;
    }
 
    int odd_level_sum = 0,
    even_level_sum = 0,
    level = 1;
 
    // queue to hold tree node with level
    Queue<Node> q = new LinkedList<Node>();
 
    // Root node is at level 1 so level=1
    q.add(root);
 
    // Do level Order Traversal of tree
    while (!q.isEmpty()) {
      int n = q.size();
      while (n-- > 0) {
        Node temp = q.peek();
        q.remove();
        if (temp.left == null
            && temp.right == null) {
          if ((level & 1) > 0) {
            odd_level_sum += temp.data;
          } else {
            even_level_sum += temp.data;
          }
          continue;
        }
        if (temp.left != null) {
          q.add(temp.left);
        }
        if (temp.right != null) {
          q.add(temp.right);
        }
      }
      level++;
    }
    System.out.println(odd_level_sum - even_level_sum);
  }
 
  // Driver Code
  public static void main(String args[]) {
    Node root = new Node(1);
    root.left = new Node(2);
    root.right = new Node(3);
    root.left.left = new Node(4);
    root.left.right = new Node(5);
    root.right.left = new Node(6);
    root.right.right = new Node(7);
    root.left.left.right = new Node(8);
    root.left.right.right = new Node(9);
    root.right.right.left = new Node(10);
    root.right.right.right = new Node(11);
    root.left.left.right.right = new Node(12);
 
    printDifference(root);
 
  }
}
 
// This code is contributed by saurabh_jaiswal.


Python3




# Python program for above approach
class Node:
    def __init__(self, key):
        self.data = key
        self.left = None
        self.right = None
 
# Utility function to create
# a new Binary Tree node
def newNode(data):
    temp = Node(data)
    return temp
 
# Function to print the difference
def printDifference(root):
    if(root is None):
        print("No nodes present")
        return
 
    odd_level_sum = 0
    even_level_sum = 0
    level = 1
 
    # queue to hold tree node with level
    q = []
 
    # Root node is at level 1 so level=1
    q.append(root)
 
    # Do level Order Traversal of tree
    while(len(q) > 0):
        n = len(q)
        while(n > 0):
            n = n-1
            temp = q.pop(0)
            if(temp.left is None and temp.right is None):
                if((level & 1) > 0):
                    odd_level_sum += temp.data
                else:
                    even_level_sum += temp.data
                continue
            if(temp.left is not None):
                q.append(temp.left)
            if(temp.right is not None):
                q.append(temp.right)
 
        level += 1
    print(odd_level_sum - even_level_sum)
 
 
# 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.left.right = newNode(8)
root.left.right.right = newNode(9)
root.right.right.left = newNode(10)
root.right.right.right = newNode(11)
root.left.left.right.right = newNode(12)
 
printDifference(root)
 
# This code is contributed by Yash Agarwal(yashagarwal2852002)


C#




// C# program for the above approach
 
using System;
using System.Collections.Generic;
 
public class GFG {
 
    // A tree node strucute
    class Node {
        public int data;
        public Node left, right;
        public Node(int d)
        {
            data = d;
            left = null;
            right = null;
        }
    }
 
    // Utility function to create a new Binary Tree node
    static Node node(int data)
    {
        Node temp = new Node(0);
        temp.data = data;
        temp.left = temp.right = null;
        return temp;
    }
 
    // Function to print the difference
    static void printDifference(Node root)
    {
        if (root == null) {
            Console.WriteLine("No nodes presesnt");
            return;
        }
        int odd_level_sum = 0;
        int even_level_sum = 0;
        int level = 1;
 
        // Queue to hold tree node with level
        Queue<Node> q = new Queue<Node>();
 
        // Root node is at level 1, so level=1.
        q.Enqueue(root);
 
        // Do level order traversal of a tree.
        while (q.Count != 0) {
            int n = q.Count;
            while (n-- > 0) {
                Node temp = q.Dequeue();
                if (temp.left == null
                    && temp.right == null) {
                    if ((level & 1) > 0) {
                        odd_level_sum += temp.data;
                    }
                    else {
                        even_level_sum += temp.data;
                    }
                    continue;
                }
                if (temp.left != null) {
                    q.Enqueue(temp.left);
                }
                if (temp.right != null) {
                    q.Enqueue(temp.right);
                }
            }
            level++;
        }
        Console.WriteLine(odd_level_sum - even_level_sum);
    }
 
    static public void Main()
    {
 
        // Code
        Node root = node(1);
        root.left = node(2);
        root.right = node(3);
        root.left.left = node(4);
        root.left.right = node(5);
        root.right.left = node(6);
        root.right.right = node(7);
        root.left.left.right = node(8);
        root.left.right.right = node(9);
        root.right.right.left = node(10);
        root.right.right.right = node(11);
        root.left.left.right.right = node(12);
 
        printDifference(root);
    }
}
 
// This code is contributed by lokesh(lokeshmvs21).


Javascript




// JavaScript program for above approach
 
// A tree node structure
class Node {
  constructor(data) {
    this.data = data;
    this.left = null;
    this.right = null;
  }
}
 
// Utility function to create
// a new Binary Tree node
function newNode(data) {
  let node = new Node(data);
  node.left = null;
  node.right = null;
 
  return node;
}
 
// Function to print the difference
function printDifference(root) {
  if (root == null) {
    console.log("No nodes present");
    return;
  }
 
  let odd_level_sum = 0,
    even_level_sum = 0,
    level = 1;
 
  // queue to hold tree node with level
  let q = [];
 
  // Root node is at level 1 so level=1
  q.push(root);
 
  // Do level Order Traversal of tree
  while (q.length > 0) {
    let n = q.length;
    while (n--) {
      let temp = q.shift();
      if (temp.left == null && temp.right == null) {
        if (level & 1) {
          odd_level_sum += temp.data;
        } else {
          even_level_sum += temp.data;
        }
        continue;
      }
      if (temp.left) {
        q.push(temp.left);
      }
      if (temp.right) {
        q.push(temp.right);
      }
    }
    level++;
  }
  console.log(odd_level_sum - even_level_sum);
}
 
// Driver Code
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.left.right = newNode(8);
root.left.right.right = newNode(9);
root.right.right.left = newNode(10);
root.right.right.right = newNode(11);
root.left.left.right.right = newNode(12);
 
printDifference(root);
 
// This code is contributed by adityamaharshi


Output

-12

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

Efficient Approach(Recursive Approach):
Follow the below steps to solve the given problem recursively:
1) Traverse the binary tree in any traversal method(Inorder, Preorder and Postorder) recursively and keep track of even and odd level at each node.
2) If found at leaf node at odd level then add this node data to oddLeafSum or if leaf found at even level then add this node data to evenLeafSum.
3) Print the difference between oddLeafSum and evenLeafSum.

Below is the implementation of above approach:

C++




// Recursive approach for the above problem
#include<bits/stdc++.h>
using namespace std;
 
struct Node {
    int data;
    Node *left, *right;
};
  
// Utility function to create
// a new Binary Tree node
Node* newNode(int data){
    Node* temp = new Node;
    temp->data = data;
    temp->left = temp->right = NULL;
    return temp;
}
 
void printDiffUtil(Node* root, int &evenLeafSum, int& oddLeafSum, int level){
    if(root == NULL) return;
    if(root->left == NULL && root->right == NULL){
        if(level == 0) evenLeafSum += root->data;
        else oddLeafSum += root->data;
    }
    if(level == 0){
        printDiffUtil(root->left, evenLeafSum, oddLeafSum, 1);
        printDiffUtil(root->right, evenLeafSum, oddLeafSum, 1);
    }else{
        printDiffUtil(root->left, evenLeafSum, oddLeafSum, 0);
        printDiffUtil(root->right, evenLeafSum, oddLeafSum, 0);
    }
}
 
void printDiff(Node* root){
    int evenLeafSum = 0;
    int oddLeafSum = 0;
    printDiffUtil(root, evenLeafSum, oddLeafSum, 1);
    cout<<oddLeafSum - evenLeafSum<<endl;
}
 
int main(){
    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->left->right = newNode(8);
    root->left->right->right = newNode(9);
    root->right->right->left = newNode(10);
    root->right->right->right = newNode(11);
    root->left->left->right->right = newNode(12);
    printDiff(root);
    return 0;
}
 
// THIS CODE IS CONTRIBUTED BY KIRTI AGARWAL(KIRTIAGARWAL23121999)


Java




import java.util.*;
 
class Node {
    int data;
    Node left, right;
 
    Node(int value)
    {
        data = value;
        left = right = null;
    }
}
 
public class Main {
    static void printDiffUtil(Node root, int[] evenLeafSum,
                              int[] oddLeafSum, int level)
    {
        if (root == null)
            return;
 
        if (root.left == null && root.right == null) {
            if (level == 0)
                evenLeafSum[0] += root.data;
            else
                oddLeafSum[0] += root.data;
        }
 
        if (level == 0) {
            printDiffUtil(root.left, evenLeafSum,
                          oddLeafSum, 1);
            printDiffUtil(root.right, evenLeafSum,
                          oddLeafSum, 1);
        }
        else {
            printDiffUtil(root.left, evenLeafSum,
                          oddLeafSum, 0);
            printDiffUtil(root.right, evenLeafSum,
                          oddLeafSum, 0);
        }
    }
 
    static void printDiff(Node root)
    {
        int[] evenLeafSum = { 0 };
        int[] oddLeafSum = { 0 };
        printDiffUtil(root, evenLeafSum, oddLeafSum, 1);
        System.out.println(oddLeafSum[0] - evenLeafSum[0]);
    }
 
    public static void main(String args[])
    {
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);
        root.right.left = new Node(6);
        root.right.right = new Node(7);
        root.left.left.right = new Node(8);
        root.left.right.right = new Node(9);
        root.right.right.left = new Node(10);
        root.right.right.right = new Node(11);
        root.left.left.right.right = new Node(12);
        printDiff(root);
    }
}


Python3




# Recursive approach for the above problem
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
# Utility function to create a new Binary Tree node
 
 
def newNode(data):
    temp = Node(data)
    return temp
 
 
def printDiffUtil(root, evenLeafSum, oddLeafSum, level):
    if not root:
        return
    # Check if node is a leaf
    if not root.left and not root.right:
        # Add the leaf node's value to the even or odd sum based on its level
        if level == 0:
            evenLeafSum[0] += root.data
        else:
            oddLeafSum[0] += root.data
    if level == 0:
        # Traverse to the next level
        printDiffUtil(root.left, evenLeafSum, oddLeafSum, 1)
        printDiffUtil(root.right, evenLeafSum, oddLeafSum, 1)
    else:
        # Traverse to the next level
        printDiffUtil(root.left, evenLeafSum, oddLeafSum, 0)
        printDiffUtil(root.right, evenLeafSum, oddLeafSum, 0)
 
 
def printDiff(root):
    # Initialize variables to store the sum of even and odd level leaf nodes
    evenLeafSum = [0]
    oddLeafSum = [0]
    # Call helper function to compute the sum of even and odd level leaf nodes
    printDiffUtil(root, evenLeafSum, oddLeafSum, 1)
    # Print the difference between the sum of odd level leaf nodes and even level leaf nodes
    print(oddLeafSum[0] - evenLeafSum[0])
 
 
# Driver code to test the program
if __name__ == '__main__':
    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.left.right = newNode(8)
    root.left.right.right = newNode(9)
    root.right.right.left = newNode(10)
    root.right.right.right = newNode(11)
    root.left.left.right.right = newNode(12)
    # Call function to print the difference between the sum of odd level leaf nodes and even level leaf nodes
    printDiff(root)


C#




using System;
 
class Node
{
  public int data;
  public Node left, right;
 
  public Node(int value)
  {
    data = value;
    left = right = null;
  }
}
 
class MainClass
{
  static void printDiffUtil(Node root, ref int evenLeafSum,
                            ref int oddLeafSum, int level)
  {
    if (root == null)
      return;
 
    if (root.left == null && root.right == null)
    {
      if (level == 0)
        evenLeafSum += root.data;
      else
        oddLeafSum += root.data;
    }
 
    if (level == 0)
    {
      printDiffUtil(root.left, ref evenLeafSum, ref oddLeafSum, 1);
      printDiffUtil(root.right, ref evenLeafSum, ref oddLeafSum, 1);
    }
    else
    {
      printDiffUtil(root.left, ref evenLeafSum, ref oddLeafSum, 0);
      printDiffUtil(root.right, ref evenLeafSum, ref oddLeafSum, 0);
    }
  }
 
  static void printDiff(Node root)
  {
    int evenLeafSum = 0;
    int oddLeafSum = 0;
    printDiffUtil(root, ref evenLeafSum, ref oddLeafSum, 1);
    Console.WriteLine(oddLeafSum - evenLeafSum);
  }
 
  public static void Main(string[] args)
  {
    Node root = new Node(1);
    root.left = new Node(2);
    root.right = new Node(3);
    root.left.left = new Node(4);
    root.left.right = new Node(5);
    root.right.left = new Node(6);
    root.right.right = new Node(7);
    root.left.left.right = new Node(8);
    root.left.right.right = new Node(9);
    root.right.right.left = new Node(10);
    root.right.right.right = new Node(11);
    root.left.left.right.right = new Node(12);
    printDiff(root);
  }
}


Javascript




class Node {
  constructor(data) {
    this.data = data;
    this.left = null;
    this.right = null;
  }
}
 
function printDiffUtil(root, evenLeafSum, oddLeafSum, level) {
  if (!root) return;
  if (!root.left && !root.right) {
    if (level === 0) evenLeafSum[0] += root.data;
    else oddLeafSum[0] += root.data;
  }
  if (level === 0) {
    printDiffUtil(root.left, evenLeafSum, oddLeafSum, 1);
    printDiffUtil(root.right, evenLeafSum, oddLeafSum, 1);
  } else {
    printDiffUtil(root.left, evenLeafSum, oddLeafSum, 0);
    printDiffUtil(root.right, evenLeafSum, oddLeafSum, 0);
  }
}
 
function printDiff(root) {
  const evenLeafSum = [0];
  const oddLeafSum = [0];
  printDiffUtil(root, evenLeafSum, oddLeafSum, 1);
  console.log(oddLeafSum[0] - evenLeafSum[0]);
}
 
const root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
root.left.left.right = new Node(8);
root.left.right.right = new Node(9);
root.right.right.left = new Node(10);
root.right.right.right = new Node(11);
root.left.left.right.right = new Node(12);
printDiff(root);


Output

-12

Time Complexity: O(N) where N is the number of nodes in given binary tree.
Auxiliary Space: O(h) where h is the height of binary tree due to recursion.



Last Updated : 13 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads