Minimize absolute difference between sum of subtrees formed after splitting Binary tree into two | Java implementation for the above approach ; Structure of Node ; Function to calculate minimum absolute difference of subtrees after splitting the tree into two parts ; Reference variable to store the answer ; Function to store sum of values of current node , left subtree and right subtree in place of current node 's value ; Function to perform every possible split and calculate absolute difference of subtrees ; Absolute difference in subtrees if left edge is broken ; Absolute difference in subtrees if right edge is broken ; Update minDiff if a difference lesser than it is found ; Driver code ; Construct the tree ; Print the output
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 ; } } } ; public static int minAbsDiff ( Node root ) { int [ ] minDiff = new int [ 1 ] ; minDiff [ 0 ] = Integer . MAX_VALUE ; postOrder ( root ) ; 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 ; int leftDiff = Math . abs ( root . left . val - ( root . val - root . left . val ) ) ; int rightDiff = Math . abs ( root . right . val - ( root . val - root . right . val ) ) ; minDiff [ 0 ] = Math . min ( minDiff [ 0 ] , Math . min ( leftDiff , rightDiff ) ) ; return ; } public static void main ( String [ ] args ) { 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 ) ; System . out . println ( minAbsDiff ( root ) ) ; } }