Mirroring BST by Insert
Write a function in C to create a new BST that is a mirror image of the given tree.
I thought about implementing this problem, which simply duplicates the root node from the original tree and then proceeds to open new nodes with DFS traversal and insert them into a new mirror tree with a different compare function (i.e. using> instead of <when ββmoving and inserting nodes) ...
My question is, will this approach work in every case? I think so, but I would like to know if there are corner cases where my solution will not work (or if there is a better solution).
source to share
Recursive solution: mirrored left and right children and assign them as right and left children (respectively) of the mirroring node. Code below (call mirrorTree (root) to execute):
class Node:
def __init__(self, val, left, right):
self.val=val
self.left=left
self.right=right
def mirrorTree(node):
new_node=None
if node:
new_node=Node(node.val, mirrorTree(node.right), mirrorTree(node.left))
return new_node
source to share
Same answer as gen-ys, but only in C.
node *create_empty()
{
node *temp = malloc(sizeof(*temp));
temp->left = left;
temp->right = right;
return temp;
}
node *add_detail(int value, node *left, node *right)
{
temp->value = value;
temp->left = left;
temp->right = right;
return temp;
}
node *mirror(node *p)
{
if (p) {
node = create_empty();
node = add_detail(p->value, mirror(p->right), mirror(p->left));
}
return node;
}
source to share