Function for flattening the tree