I have to make an implementation of the following class in C++:
struct Node {
Node* parent;
Node* left;
Node* right;
std::string name;
};
class BinaryTree {
public:
BinaryTree();
std::string ToString() const;
void RotateLeft(Node* node);
void RotateRight(Node* node);
void MakePerfect();
private:
void CreateVine();
void MakePerfectFromVine();
private:
Node *root;
};
This class implements the DSW algorithm for making a Binary tree perfect (all levels are full, except the last one)
I have done an implementation which works, I tested it and everything seem fine but I had to change the rotate functions thus:
void RotateLeft(Node*& node);
void RotateRight(Node*& node);
Unfortunately the person who set me this task said that I’m forbidden to change them. But the unaltered functions don’t work. I use them in CreateVine() and MakePerfectFromVine():
void CreateVine() {
Node *current = root;
while(current != NULL)
if(current->left != NULL){
current=current->left;
rotateRight(current);
}
else
current = current->right;
}
In this fragment the pointer current points to a node in the tree. After the node is rotated, it will have changed its parent and/or left and/or right child, but current will point to the old node with the old information. In order for the changes made in the rotate function to be reflected outside of the rotate function, I have to use reference-to-pointer, pointer-to-pointer or the function itself has to return the node;
The only way I can think of to fix this problem is if I know that the binary tree doesn’t allow duplicate elements, after I rotate the node I search for its string value and set current to point to it, but I’m not sure if the binary tree doesn’t allow duplicate elements and that would increase the time complexity of the algorithm.
Is there any way of avoiding the use of reference-to-pointer and pointer-to-pointer?
Excluding the root of the tree, for which you might have to think something else, the pointer to a given node inside the tree can be obtained with an extra level of indirection:
So you can actually maintain your algorithm and just resolve the reference doing this inside the function. Note that this is a sketch, you will have to check for the root (
parent==0) and operate differently there