How to check whether the tree is symmetric or not using recursion in C#?


In the recursive approach we to find a tree is symmetric or not we initially check whether the tree is null or not, if the tree is null then its symmetric, if the tree is not not null we call amethod issymmetricmirror .In isSymmetricMirror we get the value of the left child and right child, if both left and right child are null we consider as symmetric, if either of the value is null then we consider and not symmetric and at last we call the issymmetric method recursively by passing the left and right child values.

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 bool isSymmetricRecursive(Node node)
   {
      if (node == null){
         return true;
      }
      return isSymmetricMirror(node.LeftChild, node.RightChild);
   }
   private bool isSymmetricMirror(Node node1, Node node2){
      if (node1 == null && node2 == null){
         return true;
      }
      if (node1 == null || node2 == null){
         return false;
      }
      if (node1.Value != node2.Value){
         return false;
      }
      return isSymmetricMirror(node1.LeftChild, node2.RightChild) && isSymmetricMirror(node2.LeftChild, node1.RightChild);
   }
}

Output

      1
    2  2
   3 4 4 3
True

Updated on: 17-Aug-2021

134 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements