I would indeed separate the ownership of the objects from the algorithm itself.
In case you know for sure you will have a fixed number of nodes during the algorithm's execution, you can use vector<TreeNode>
which is created once, fully, beforehand.
Then you can either use pointers to the elements or their indices and operate on those.
Pointers are slightly more flexible as then you can change the underlying storage container to something non-contiguous (e.g. std::set
, or even store them in a map
or something else entirely).
Then no extra visual and code overhead "pollutes" the algorithm code unnecessarily, and the ownership question is trivial, which is always a good thing.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…