Remove all nodes which don 't lie in any path with sum>= k | A utility function to create a new Binary Tree node with given data ; print the tree in LVR ( Inorder traversal ) way . ; Main function which truncates the binary tree . ; Base Case ; Initialize left and right Sums as Sum from root to this node ( including this node ) ; Recursively prune left and right subtrees ; Get the maximum of left and right Sums ; If maximum is smaller than k , then this node must be deleted ; A wrapper over pruneUtil ( ) ; Driver Code ; k is 45
class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def Print ( root ) : NEW_LINE INDENT if ( root != None ) : NEW_LINE INDENT Print ( root . left ) NEW_LINE print ( root . data , end = " ▁ " ) NEW_LINE Print ( root . right ) NEW_LINE DEDENT DEDENT def pruneUtil ( root , k , Sum ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT lSum = [ Sum [ 0 ] + ( root . data ) ] NEW_LINE rSum = [ lSum [ 0 ] ] NEW_LINE root . left = pruneUtil ( root . left , k , lSum ) NEW_LINE root . right = pruneUtil ( root . right , k , rSum ) NEW_LINE Sum [ 0 ] = max ( lSum [ 0 ] , rSum [ 0 ] ) NEW_LINE if ( Sum [ 0 ] < k [ 0 ] ) : NEW_LINE INDENT root = None NEW_LINE DEDENT return root NEW_LINE DEDENT def prune ( root , k ) : NEW_LINE INDENT Sum = [ 0 ] NEW_LINE return pruneUtil ( root , k , Sum ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT k = [ 45 ] NEW_LINE root = newNode ( 1 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 3 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 5 ) NEW_LINE root . right . left = newNode ( 6 ) NEW_LINE root . right . right = newNode ( 7 ) NEW_LINE root . left . left . left = newNode ( 8 ) NEW_LINE root . left . left . right = newNode ( 9 ) NEW_LINE root . left . right . left = newNode ( 12 ) NEW_LINE root . right . right . left = newNode ( 10 ) NEW_LINE root . right . right . left . right = newNode ( 11 ) NEW_LINE root . left . left . right . left = newNode ( 13 ) NEW_LINE root . left . left . right . right = newNode ( 14 ) NEW_LINE root . left . left . right . right . left = newNode ( 15 ) NEW_LINE print ( " Tree ▁ before ▁ truncation " ) NEW_LINE Print ( root ) NEW_LINE print ( ) NEW_LINE root = prune ( root , k ) NEW_LINE print ( " Tree ▁ after ▁ truncation " ) NEW_LINE Print ( root ) NEW_LINE DEDENT