KatInterview

563. Binary Tree Tilt

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem requires us to calculate the sum of the "tilt" of every node in a binary tree. The tilt of a single node is defined as the absolute difference between the sum of all values in its left subtree and the sum of all values in its right subtree.

Solution

Binary Tree Tilt in Python

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def findTilt(self, root: Optional[TreeNode]) -> int:
        # Initialize total tilt as a member variable to be accessible in the helper function.
        self.total_tilt = 0

        # Helper function to perform post-order traversal.
        # It returns the sum of the subtree rooted at 'node'
        # and updates self.total_tilt as a side effect.
        def post_order_sum(node: Optional[TreeNode]) -> int:
            if not node:
                return 0
            
            # Recursively find the sum of left and right subtrees
            left_sum = post_order_sum(node.left)
            right_sum = post_order_sum(node.right)
            
            # Calculate the tilt for the current node and add to total
            tilt = abs(left_sum - right_sum)
            self.total_tilt += tilt
            
            # Return the sum of the subtree rooted at 'node' to its parent
            return node.val + left_sum + right_sum

        # Start the traversal from the root
        post_order_sum(root)
        
        return self.total_tilt

Binary Tree Tilt in Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    private int totalTilt = 0;

    public int findTilt(TreeNode root) {
        postOrderSum(root);
        return this.totalTilt;
    }

    /**
     * Helper function to perform post-order traversal.
     * It returns the sum of the subtree rooted at 'node'
     * and updates the totalTilt as a side effect.
     */
    private int postOrderSum(TreeNode node) {
        if (node == null) {
            return 0;
        }

        // Recursively find the sum of left and right subtrees
        int leftSum = postOrderSum(node.left);
        int rightSum = postOrderSum(node.right);

        // Calculate the tilt for the current node and add it to the total tilt
        int tilt = Math.abs(leftSum - rightSum);
        this.totalTilt += tilt;

        // Return the sum of the subtree rooted at 'node' to its parent
        return node.val + leftSum + rightSum;
    }
}

Binary Tree Tilt in C++

/**
 * 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 {
private:
    int totalTilt = 0;

    // Helper function to perform post-order traversal.
    // It returns the sum of the subtree rooted at 'node'
    // and updates the totalTilt as a side effect.
    int postOrderSum(TreeNode* node) {
        if (node == nullptr) {
            return 0;
        }

        // Recursively find the sum of left and right subtrees
        int leftSum = postOrderSum(node->left);
        int rightSum = postOrderSum(node->right);

        // Calculate the tilt for the current node and add it to the total tilt
        int tilt = abs(leftSum - rightSum);
        totalTilt += tilt;

        // Return the sum of the subtree rooted at 'node' to its parent
        return node->val + leftSum + rightSum;
    }

public:
    int findTilt(TreeNode* root) {
        postOrderSum(root);
        return totalTilt;
    }
};

Binary Tree Tilt in TypeScript

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function findTilt(root: TreeNode | null): number {
    // Use a variable in the outer scope to accumulate the total tilt.
    // This variable will be captured by the inner helper function's closure.
    let totalTilt = 0;

    /**
     * Helper function to perform post-order traversal.
     * It returns the sum of the subtree rooted at 'node'
     * and updates totalTilt as a side effect.
     */
    function postOrderSum(node: TreeNode | null): number {
        if (node === null) {
            return 0;
        }

        // Recursively find the sum of left and right subtrees
        const leftSum = postOrderSum(node.left);
        const rightSum = postOrderSum(node.right);

        // Calculate the tilt for the current node and add to total
        const tilt = Math.abs(leftSum - rightSum);
        totalTilt += tilt;

        // Return the sum of the subtree rooted at 'node' to its parent
        return node.val + leftSum + rightSum;
    }

    // Start the traversal from the root
    postOrderSum(root);

    return totalTilt;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.