Made significant changes to Flatten_tree function