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


In the Iterative approach we have to create 2 Queues, one queue saves the left child and another queue saves the right child value. If the tree is empty, then it is symmetrical to the vertical axis going through its root node. Else, check if the value at the root node of both subtrees is the same. If it is, then check if the left subtree and the right subtree are symmetrical. Enqueue the left child value and right child value into the queue1 and enqueue the right child and left child value into the queue1

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 isSymmetricIterative(Node node){
      if (node == null){
         return true;
      }
      Queue<Node> Q1 = new Queue<Node>);
      Queue<Node> Q2 = new Queue<Node>();
      Q1.Enqueue(node.LeftChild);
      Q2.Enqueue(node.RightChild);
      while (Q1.Count > 0 && Q2.Count > 0){
         Node n1 = Q1.Dequeue();
         Node n2 = Q2.Dequeue();
         if ((n1 == null && n2 != null) || n1 != null && n2 == null){
            return false;
         }
         if (n1 != null){
            if (n1.Value != n2.Value){
               return false;
            }
            Q1.Enqueue(n1.LeftChild);
            Q1.Enqueue(n1.RightChild);
            Q1.Enqueue(n1.RightChild);
            Q1.Enqueue(n1.LeftChild);
         }
      }
      return true;
   }
}

Output

      1
     2 2
   3 4 4 3
True

Updated on: 17-Aug-2021

87 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements