Categories:

Tags:



Problem

Given the root of a binary tree, return the sum of every tree node’s tilt.

The tilt of a tree node is the absolute difference between the sum of all left subtree node values and all right subtree node values. If a node does not have a left child, then the sum of the left subtree node values is treated as 0. The rule is similar if the node does not have a right child.

Constraints

  • The number of nodes in the tree is in the range [0, 104].
  • -1000 <= Node.val <= 1000

Solution

The problem Binary Tree Tilt can be solved using a recursion to keep track of sum of all subtree nodes and the sum of every tree node’s tilt.

Implementation

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
  public:
    int helper(TreeNode *root, int &tilt)
    {
        if (root == NULL)
            return 0;

        int lsum = helper(root->left, tilt);
        int rsum = helper(root->right, tilt);

        tilt += abs(lsum - rsum);
        return root->val + lsum + rsum;
    }

    int findTilt(TreeNode *root)
    {
        int tilt = 0;
        helper(root, tilt);

        return tilt;
    }
};