There's tons of info on how to mirror it, but those assume that node->left and node->right can be modified, such as this function (not mine, copied from another website).
void mirror(struct Node* node) {
if (node==NULL) return;
else {
struct Node* temp;
/* do the subtrees */
mirror(node->left);
mirror(node->right);
/* swap the pointers in this node */
temp = node->left;
node->left = node->right;
node->right = temp;
}
}
I know there has to be recursion and a base case (basically the "do the subtrees" part) but I have no idea how to do the actual swapping since Node is a class with the left and right subtrees being private (can't change that).
For reference, this is the class constructor (there's no default constructor). I can provide more functions if they're important (there are accessor functions but no mutators). It also uses templates, hence the T.
Node(const T &x, Node *L = 0, Node *R = 0) : data(x), left(L), right(R) {}
I also made two other functions (treeHeight and countNodes), don't know if that's relevant. And I have to make a new tree to return, not modify the original tree.
Note - I did not want to provide this as an answer but wanted to inform the OP about C++ syntax
You originally had this for your function:
void mirror(struct Node* node) { if (node==NULL) return; else { struct Node* temp; /* do the subtrees */ mirror(node->left); mirror(node->right); /* swap the pointers in this node */ temp = node->left; node->left = node->right; node->right = temp; } }
In C++
you do not need to use the keyword struct
when declaring it as a function-parameter
nor as a declaration
of a variable
. You only need it when you are writing the declaration
to the struct
or class
itself. You can simply do this:
void mirror(Node* node) {
if (node==NULL) return;
else {
Node* temp;
/* do the subtrees */
mirror(node->left);
mirror(node->right);
/* swap the pointers in this node */
temp = node->left;
node->left = node->right;
node->right = temp;
}
}