Rapid urbanization and global climate change are likely to exacerbate urban flooding intensity, frequency and uncertainty. Thus, it is fundamental and crucial to investigate the dominant influencing factors for the mitigation of urban flooding. However, knowledge about the influence of building patterns on urban flooding remains limited. Taking Beijing, a typical megacity, as a case study area, we quantified the importance of building patterns and their interaction effect at the subwatershed scale using the boosted regression tree and geographical detector model. The results indicated that (1) the landscape shape index, slope, green space ratio and waterbody ratio were the most important influencing factors determining urban flooding, with a total relative contribution of 67.23%; (2) building metrics had a certain impact on urban flooding, and the sum of the relative contribution reached 21.03%; (3) the landscape shape index, slope, and green space ratio exhibited a combination of negative and positive correlations with urban flooding density; and (4) an enhancement effect existed between building metrics, especially the building congestion degree and building density. These findings provide quantitative insights on rational urban morphology planning which could be applied to improve stormwater management and promote urban sustainability in megacities.