In medicine, high-quality images are crucial for accurate clinical diagnosis, making lossless compression essential to preserve image integrity. Neural networks, with their powerful probabilistic estimation capabilities, seamlessly integrate with entropy encoders to achieve lossless compression. Recent studies have demonstrated that this approach outperforms traditional compression algorithms. However, existing methods have yet to adequately address the issue of inaccurate probabilistic estimation by neural networks when processing edge or complex textured regions. This limitation leaves significant room for improvement in compression performance. To address these challenges, this study proposes a novel lossless image compression method that employs a flexible tree-structured image segmentation mechanism. Due to the close relationships between subimages, this mechanism allows neural networks to fully exploit the prior knowledge of encoded subimages, thereby improving the accuracy of probabilistic estimation in complex textured regions of unencoded subimages. In terms of network architecture, we have introduced an attention mechanism into the UNet network to enhance the accuracy of probabilistic estimation across the entire subimage regions. Additionally, the flexible tree-structured image segmentation mechanism enabled us to implement variable-speed compression. We provide benchmarks for both fast and slow compression modes. Experimental results indicate that the proposed method achieves state-of-the-art compression speed in the fast mode. In the slow mode, it attains stateof-the-art performance.