The Wayback Machine - https://web.archive.org/web/20210829052616/https://www.geeksforgeeks.org/minimize-absolute-difference-between-sum-of-subtrees-formed-after-splitting-binary-tree-into-two/
Skip to content
Related Articles

Related Articles

Improve Article

Minimize absolute difference between sum of subtrees formed after splitting Binary tree into two

  • Last Updated : 28 Aug, 2021

Given a binary tree consisting of N nodes, the task is to split the binary tree into two subtrees by removing one edge such that the absolute difference of the sum of the subtrees is minimized.

Example:

Input:      1
               /   \
             2     3
           /  \      \
         4    5     8
                    /  \
                  6    7 
Output: 6
Explanation: Split the tree between vertex 3 and 8. Subtrees created have sums 21 and 15

Input:        1
               /    \
             2       3
           /  \     /  \
        4     5  6    7
                      
Output: 4
Explanation: Split the tree between vertex 1 and 3. Subtrees created have sums 16 and 12

Approach: Given problem can be solved by following the steps below:



  • Initialize variable minDiff to maximum value of Integer which will store the answer
  • Use postorder traversal to store the sum of current node, left subtree and right subtree in the current node
  • Use preorder traversal and at every recursive call find the sum of subtrees if the split is between:
    • current node and left child node
    • current node and right child node
  • Update minDiff if at any recursive call the difference of subtrees is less than minDiff

Below is the implementation of the above approach:

Java




// Java implementation for the above approach
import java.lang.Math;
import java.io.*;
  
class GFG {
  
    static class Node {
        Node left, right;
        int val;
        public Node(int val)
        {
            this.val = val;
            this.left = this.right = null;
        }
    }
  
    // Function to calculate minimum absolute
    // difference of subtrees after
    // splitting the tree into two parts
    public static int minAbsDiff(Node root)
    {
  
        // Reference variable
        // to store the answer
        int[] minDiff = new int[1];
  
        minDiff[0] = Integer.MAX_VALUE;
  
        // Function to store sum of values
        // of current node, left subtree and
        // right subtree in place of
        // current node's value
        postOrder(root);
  
        // Function to perform every
        // possible split and calculate
        // absolute difference of subtrees
        preOrder(root, minDiff);
  
        return minDiff[0];
    }
  
    public static int postOrder(Node root)
    {
        if (root == null)
            return 0;
        root.val += postOrder(root.left)
                    + postOrder(root.right);
        return root.val;
    }
  
    public static void preOrder(Node root,
                                int[] minDiff)
    {
        if (root == null)
            return;
  
        // Absolute difference in subtrees
        // if left edge is broken
        int leftDiff
            = Math.abs(root.left.val
                       - (root.val - root.left.val));
  
        // Absolute difference in subtrees
        // if right edge is broken
        int rightDiff
            = Math.abs(root.right.val
                       - (root.val - root.right.val));
  
        // Update minDiff if a difference
        // lesser than it is found
        minDiff[0]
            = Math.min(minDiff[0],
                       Math.min(leftDiff, rightDiff));
  
        return;
    }
  
    // Driver code
    public static void main(String[] args)
    {
        // Construct the tree
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);
        root.right.left = new Node(6);
        root.right.right = new Node(7);
  
        // Print the output
        System.out.println(minAbsDiff(root));
    }
}
Output:
4

Time Complexity: O(N)  
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :