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?

    1 answer 1

    In my opinion, there is simply not enough yet another redirection level.

     assert(nullptr != p_node); auto pp_node{::std::addressof(p_node)); do { if(0 == (static_cast<unsigned int>(rand()) bitand 1u)) { pp_node = ::std::addressof((**pp_node).left); } else { pp_node = ::std::addressof((**pp_node).right); } } while(nullptr != (*pp_node)); (*pp_node) = new BinaryTree; 

    Well and still the condition while (nullptr == accessoryPtr) cannot be correct as if accessoryPtr is not zero, then the cycle will not be executed, and if zero - then inside the cycle it will be dereferenced.