Refactor step 4 of build_tree into enumerate_nodes_and_leaves().