Fix to tree flattening algorithm