Given a randomly distributed set of keys, with each key mapped to a set of values, how would you transform it into multiple trees?
Example Data Set
- NB2 => {NC2 ND2}
- ND1 => {NG1 NH1}
- NA1 => {NB1}
- NB1 => {NC1 ND1 NE1}
- NA2 => {NB2}
- NC1 => {NF1}
- NE1 => {NI1 NJ1 NK1}
Resulting Tree for NA1
NA1
`-- NB1
|-- NC1
| `-- NF1
|-- ND1
| |-- NG1
| `-- NH1
`-- NE1
|-- NI1
|-- NJ1
`-- NK1
Resulting Tree for NA2
NA2
`-- NB2
|-- NC2
`-- ND2
I’m not aware of any library methods that will do this transformation. Here’s how I’d do it. It’s pretty straightforward, IMO.
EDIT: Note this algorithm will “work” if the input represents a set of DAGs (Directed Acyclic Graphs). However, I’ve just realized that the resulting a set of trees will share TreeNode instances for any common subtrees in the input data.
Beware that I haven’t debugged this code 🙂