what is the approach or algorithm if we need to store all the selected leaves ids and their parents ids recursively?