Remove all nodes which don 't lie in any path with sum>= k | binary tree node contains data field , left and right pointer ; inorder traversal ; Function to remove all nodes which do not lie in th sum path ; Base case ; Recur for left and right subtree ; if node is leaf and sum is found greater than data than remove node An important thing to remember is that a non - leaf node can become a leaf when its children are removed ; Driver program to test above function
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def inorder ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return NEW_LINE DEDENT inorder ( root . left ) NEW_LINE print ( root . data , " " , end = " " ) NEW_LINE inorder ( root . right ) NEW_LINE DEDENT def prune ( root , sum ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return None NEW_LINE DEDENT root . left = prune ( root . left , sum - root . data ) NEW_LINE root . right = prune ( root . right , sum - root . data ) NEW_LINE if root . left is None and root . right is None : NEW_LINE INDENT if sum > root . data : NEW_LINE INDENT return None NEW_LINE DEDENT DEDENT return root 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 root . left . left . left = Node ( 8 ) NEW_LINE root . left . left . right = Node ( 9 ) NEW_LINE root . left . right . left = Node ( 12 ) NEW_LINE root . right . right . left = Node ( 10 ) NEW_LINE root . right . right . left . right = Node ( 11 ) NEW_LINE root . left . left . right . left = Node ( 13 ) NEW_LINE root . left . left . right . right = Node ( 14 ) NEW_LINE root . left . left . right . right . left = Node ( 15 ) NEW_LINE print ( " Tree ▁ before ▁ truncation " ) NEW_LINE inorder ( root ) NEW_LINE prune ( root , 45 ) NEW_LINE print ( " Tree after truncation " ) NEW_LINE inorder ( root ) NEW_LINE