Minimize absolute difference between sum of subtrees formed after splitting Binary tree into two | Python3 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 ; Construct the tree ; Print the output
import sys NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , val ) : NEW_LINE INDENT self . val = val NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def minAbsDiff ( root ) : NEW_LINE INDENT minDiff = [ 0 ] * ( 1 ) NEW_LINE minDiff [ 0 ] = sys . maxsize NEW_LINE postOrder ( root ) NEW_LINE preOrder ( root , minDiff ) NEW_LINE return minDiff [ 0 ] NEW_LINE DEDENT def postOrder ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT root . val += postOrder ( root . left ) + postOrder ( root . right ) NEW_LINE return root . val NEW_LINE DEDENT def preOrder ( root , minDiff ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT leftDiff = abs ( root . left . val - ( root . val - root . left . val ) ) NEW_LINE rightDiff = abs ( root . right . val - ( root . val - root . right . val ) ) NEW_LINE minDiff [ 0 ] = min ( minDiff [ 0 ] , min ( leftDiff , rightDiff ) ) NEW_LINE return NEW_LINE DEDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . left . right = Node ( 5 ) NEW_LINE root . right . left = Node ( 6 ) NEW_LINE root . right . right = Node ( 7 ) NEW_LINE print ( minAbsDiff ( root ) ) NEW_LINE