This looks like a problem best solved with a binary tree
https://i.imgur.com/3GN5AMQ.png