Minimize absolute difference between sum of subtrees formed after splitting Binary tree into two | 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 ; Construct the tree ; Print the output
class Node { constructor ( val ) { this . left = null ; this . right = null ; this . val = val ; } } function minAbsDiff ( root ) { let minDiff = new Array ( 1 ) ; minDiff [ 0 ] = Number . MAX_VALUE ; postOrder ( root ) ; preOrder ( root , minDiff ) ; return minDiff [ 0 ] ; } function postOrder ( root ) { if ( root == null ) return 0 ; root . val += postOrder ( root . left ) + postOrder ( root . right ) ; return root . val ; } function preOrder ( root , minDiff ) { if ( root == null ) return ; let leftDiff = Math . abs ( root . left . val - ( root . val - root . left . val ) ) ; let rightDiff = Math . abs ( root . right . val - ( root . val - root . right . val ) ) ; minDiff [ 0 ] = Math . min ( minDiff [ 0 ] , Math . min ( leftDiff , rightDiff ) ) ; return ; } let 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 ) ; document . write ( minAbsDiff ( root ) ) ;