Tilt of Binary Tree

Given a binary tree, return the tilt of the whole tree. The tilt of a tree node is defined as the absolute difference between the sum of all left subtree node values and the sum of all right subtree node values. Null nodes are assigned tilt to be zero. Therefore, tilt of the whole tree is defined as the sum of all nodes’ tilt.

Examples:

Input :

    1
   / \
  2   3
  
Output : 1
Explanation: 
Tilt of node 2 : 0
Tilt of node 3 : 0
Tilt of node 1 : |2-3| = 1
Tilt of binary tree : 0 + 0 + 1 = 1

Input :

    4
   / \
  2   9
 / \   \
3   5   7

Output : 15
Explanation: 
Tilt of node 3 : 0
Tilt of node 5 : 0
Tilt of node 7 : 0
Tilt of node 2 : |3-5| = 2
Tilt of node 9 : |0-7| = 7
Tilt of node 4 : |(3+5+2)-(9+7)| = 6
Tilt of binary tree : 0 + 0 + 0 + 2 + 7 + 6 = 1
class Solution {
    static class Pair {
        int sum;
        int tilt;
    }

    int treeTilt;

    public int treeTilt(Node node) {
        treeTilt = 0;
        helper(node);
        return treeTilt;
    }

    public Pair helper(Node node) {
        if (node == null) 
            return new Pair();
        Pair root = new Pair();
        Pair left = solve2(node.left);
        Pair right = solve2(node.right);
        root.sum = node.data + left.sum + right.sum;
        root.tilt = Math.abs(left.sum - right.sum);
        treeTilt += root.tilt;
        return root;
    }
}

Last updated