How to invert a binary search tree using recursion in C#?


To invert a binary search tree, we call a method InvertABinarySearchTree which takes node as a parameter. If the node is null then return null, if the node is not null, we call the InvertABinarySearchTree recursively by passing the left and right child values. and assign the right child value to the left child and left child value to the right child. The final output will consist of the tree which will be its own mirror image.

Example

public class TreesPgm{
   public class Node{
      public int Value;
      public Node LeftChild;
      public Node RightChild;
      public Node(int value){
         this.Value = value;
      }  
      public override String ToString(){
         return "Node=" + Value;
      }
   }
   public Node InvertABinarySearchTree(Node node){
      if (node == null){
         return null;
      }
      Node left = InvertABinarySearchTree(node.LeftChild);
      Node right = InvertABinarySearchTree(node.RightChild);
      node.LeftChild = right;
      node.RightChild = left;
      return root;
   }
}

Input

   1
  3 2

Output

   1
  2 3

Updated on: 17-Aug-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements