Write a function in C to create a new BST which is the mirror image of a given tree.
I thought of an implementation for this problem which just duplicates the root node from the original tree and then proceeds by discovering new nodes with a DFS traversal and inserting them into the new mirror tree with a different comparison function (i.e. using > instead of < when traversing and inserting nodes).
My question is: will this approach work in every case? I think so but I'd like to know if there are corner cases where my solution will not work (or if there's a better solution).
Recursive solution: mirror left and right children and assign them as right and left children (respectively) of mirrored 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With