I am writing a simple implementation of a binary tree. I have the code:
void makeBinaryTree(BinaryTree *node, int numOfVertices) { while (0 < numOfVertices--) { auto accessoryPtr = node; while (nullptr == accessoryPtr) { if (static_cast<double>(rand()) / RAND_MAX < 0.5) { accessoryPtr = accessoryPtr->left;//Тут } else { accessoryPtr = accessoryPtr->right;//и тут } } accessoryPtr = new BinaryTree; std::cout << "Enter value "; std::cin >> accessoryPtr->data; } }
here I cyclically randomly select which place the next vertex will be inserted. When I find a vertex with an empty subtree selected equal to nullptr
(when I create a vertex, I immediately initialize its subtrees nullptr
) I want to get its alias, exit the loop and allocate memory for it.
In this code, I just take the pointer, respectively, after allocating memory for accessoryPtr
, it will point to some other place in memory, and this will not affect the node
.
Alternatively, one could write a function:
void makeNodeOfBinaryTree(BinaryTree *&node) { node = new BinaryTree; std::cout << "Enter value "; std::cin >> node->data; }
and then, the branch in which I wanted to get a pointer alias will look like this:
if (accessoryPtr->left == nullptr) { makeNodeOfBinaryTree(accessoryPtr->left); break; } accessoryPtr = accessoryPtr->left;
However, further on the code I again meet with a similar problem and there such a solution will no longer work. Ideally, of course, to rewrite everything is fine, but it's just interesting to find out if there is a possibility of getting the alias I need?