Difference between sums of odd level and even level nodes of a Binary Tree in Java

Given a binary tree, find the difference between the sum of nodes at odd levels and the sum of nodes at even levels. The root is at level 1 (odd), its children are at level 2 (even), and so on.

Problem Statement

The tree structure for our example is −

Level 1 (odd) Level 2 (even) Level 3 (odd) Level 4 (even) 5 2 6 1 4 8 3 7 9
Odd level sum  (1,3) = 5 + 1 + 4 + 8 = 18
Even level sum (2,4) = 2 + 6 + 3 + 7 + 9 = 27

Difference = 18 - 27 = -9

Solution

Use recursive traversal. At each node, return the node's value minus the recursive results of its left and right children. This works because at each level the sign alternates − the current node adds its value, and subtracting the children's results flips the sign for the next level.

Java Implementation

The following program implements this recursive approach ?

class Node {
    int data;
    Node left, right;
    Node(int data) {
        this.data = data;
        this.left = this.right = null;
    }
}

public class JavaTester {
    public static Node getTree() {
        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.left.left = new Node(3);
        root.right.right = new Node(8);
        root.left.right.left = new Node(7);
        root.left.right.right = new Node(9);
        return root;
    }

    public static int difference(Node node) {
        if (node == null) return 0;
        return node.data - difference(node.left) - difference(node.right);
    }

    public static void main(String args[]) {
        Node tree = getTree();
        System.out.println("Difference: " + difference(tree));
    }
}

The output of the above code is ?

Difference: -9

Conclusion

The recursive approach elegantly computes the odd-even level difference by subtracting children's results at each node, automatically alternating the sign at each level. This runs in O(n) time where n is the number of nodes in the tree.

Updated on: 2026-03-14T12:55:33+05:30

484 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements