expertfunda logo Top Interview Questions Binary Tree Binary Search Tree Graph

Binary Tree Tilt

Leetcode 563. Binary Tree Tilt

Binary Tree Tilt

Leetcode 563. Binary Tree Tilt : 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.

Approach 1: Post-Order DFS Traversal:


class Solution {
    private int totalTilt = 0;

    protected int valueSum(TreeNode node) {
        if (node == null)
            return 0;

        int leftSum = this.valueSum(node.left);
        int rightSum = this.valueSum(node.right);
        int tilt = Math.abs(leftSum - rightSum);
        this.totalTilt += tilt;

        // return the sum of values starting from this node.
        return node.val + leftSum + rightSum;
    }

    public int findTilt(TreeNode root) {
        this.totalTilt = 0;
        this.valueSum(root);
        return this.totalTilt;
    }
}

Time Complexity: O(n) and Space Complexity: O(n)


See Video lecture


Leetcode 563. Binary Tree Tilt

Introduction

The "Binary Tree Tilt" problem asks to find the tilt of a binary tree. The tilt of a tree node is defined as the absolute difference between the sum of the values of its left and right subtrees. The tilt of the entire tree is the sum of the tilts of all its nodes.

This problem is typically solved using a depth-first traversal of the tree and calculating the tilt at each node recursively. The challenge is to efficiently compute the tilt while traversing the tree only once.

Problem Statement

Given the root of a binary tree, return the tilt of the tree. The tilt of the tree is the sum of the tilt of each node. The tilt of a node is defined as the absolute difference between the sum of the nodes in its left subtree and the sum of the nodes in its right subtree.

        class TreeNode:
            def __init__(self, val=0, left=None, right=None):
                self.val = val
                self.left = left
                self.right = right
        

The tree node structure is defined as above. The task is to calculate the tilt of the binary tree.

Approach

The approach to solve the problem can be broken down into a few key steps:

  • If the node is null, its tilt is 0, so return 0.
  • Recursively calculate the sum of values of the left and right subtrees of each node.
  • For each node, calculate its tilt as the absolute difference between the sum of the values of its left and right subtrees.
  • Accumulate the tilt of all nodes as you traverse the tree.

This approach ensures that we compute the sum of the subtree values as well as the tilt of each node during a single traversal of the tree.

Algorithm

The algorithm proceeds as follows:

  1. Traverse the tree using a post-order traversal (left, right, root).
  2. At each node, calculate the sum of its left and right subtrees.
  3. Calculate the tilt of the current node as the absolute difference between the left and right subtree sums.
  4. Return the sum of the tilt of the current node and the tilt of its subtrees to the parent node.
  5. Accumulate the tilt of each node into a global variable or a class attribute to keep track of the total tilt of the tree.

This approach ensures that we process each node once and calculate its tilt efficiently.

Example

Consider the following binary tree:

               1
              / \
             2   3
            / \
           4   5
        

- The tilt of node 4 is 0 (no children). - The tilt of node 5 is 0 (no children). - The tilt of node 2 is |4 + 5 - 0| = 9. - The tilt of node 3 is 0 (no children). - The tilt of node 1 is |(2 + 9) - 3| = 8. - The total tilt of the tree is 0 + 0 + 9 + 0 + 8 = 17.

In this example, the tilt of the entire tree is 17.

Code Implementation

Below is the Python code to calculate the tilt of a binary tree:

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def __init__(self):
        self.total_tilt = 0
    
    def findTilt(self, root):
        # Helper function to calculate the sum of values of each subtree
        def subtree_sum(node):
            if not node:
                return 0
            left_sum = subtree_sum(node.left)
            right_sum = subtree_sum(node.right)
            tilt = abs(left_sum - right_sum)
            self.total_tilt += tilt
            return left_sum + right_sum + node.val
        
        subtree_sum(root)
        return self.total_tilt
        

In this code: - The `subtree_sum` function recursively calculates the sum of the subtree rooted at each node. - At each node, the tilt is calculated as the absolute difference between the left and right subtree sums, and it is added to the `total_tilt`. - The `findTilt` function initiates the recursion and returns the total tilt of the tree.

Time Complexity

The time complexity of this solution is O(n), where n is the number of nodes in the binary tree. This is because we visit each node exactly once during the post-order traversal.

The space complexity is O(h), where h is the height of the tree, due to the recursion stack. In the worst case, for an unbalanced tree, the height will be O(n), resulting in a space complexity of O(n). For a balanced tree, the height will be O(log n), so the space complexity will be O(log n).

Optimized Approach

The current approach is already optimal in terms of time complexity, as we only need to visit each node once. However, if we need to reduce the space complexity, we could attempt to solve the problem iteratively using a stack, although the recursive solution is straightforward and concise.

The space complexity is primarily dependent on the recursion stack, which could be optimized by using an iterative approach, but the current approach is efficient in both time and space for most cases.

Time Complexity (Optimized)

The time complexity remains O(n), where n is the number of nodes in the tree. The space complexity is O(h), where h is the height of the tree, which can be O(n) in the worst case (for an unbalanced tree) and O(log n) for a balanced tree.

Conclusion

The "Binary Tree Tilt" problem is a relatively straightforward problem that involves calculating the tilt of a binary tree by summing the tilts of each node. The solution involves a recursive traversal of the tree, calculating the sum of the left and right subtrees, and accumulating the tilt at each node. The time complexity is O(n), where n is the number of nodes, and the space complexity is O(h), where h is the height of the tree due to the recursion stack.