Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mirroring BSTs by insertion

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).

like image 511
Avery O. Avatar asked Apr 25 '26 14:04

Avery O.


1 Answers

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
like image 57
gen-y-s Avatar answered Apr 28 '26 06:04

gen-y-s



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!