auto select ancestor category on selecting leaf category

I need a module that make it possible to select only leaf category and when this happens it should auto select all their ancestors category, in the product creation page.
How to do that for a custom module? What are the class to override?