
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if a Tree is Symmetric 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
Advertisements