Difference Between Sum of Odd Level and Even Level Nodes

Java Implementation of finding the difference sum of odd level nodes and sum of even level nodes.

import java.util.LinkedList;
import java.util.Queue;

class Solution
{
    static class TreeNode{
        int data;
        TreeNode left,right;
        TreeNode(int data)
        {
            this.data=data;
        }
    }
    static int OddEvenLevelDifference(TreeNode root)
    {
        Queue<TreeNode> queue=new LinkedList<>();
        queue.add(root);
        int level=0;
        int odd=0,even=0;
        while(!queue.isEmpty())
        {
            int s=queue.size();
            level++;
            int levelsum=0;
            for(int i=0;i<s;i++)
            {
                
                TreeNode temp=queue.poll();
                if(temp.left!=null)
                queue.add(temp.left);
                if(temp.right!=null)
                queue.add(temp.right);
                
                levelsum=levelsum+temp.data;
            }
            if(level%2==0)
                even=even+levelsum;
            else
                odd=odd+levelsum;           
        }
        return odd-even;
    }
     public static void main(String[] args)
    {
        TreeNode root=new TreeNode(1);
        root.left=new TreeNode(2);
        root.right=new TreeNode(3);
        root.left.left=new TreeNode(4);
        root.left.right=new TreeNode(7);
        
        int diff=OddEvenLevelDifference(root);
        System.out.println(diff);
        
         
    }
    }

Output: 7

Time Complexity- O(n)

Space Complexity- O(n)

Leave a comment

Your email address will not be published. Required fields are marked *

Pin It on Pinterest