Given an N-ary tree root, the task is to check if it is symmetric horizontally (Mirror image of itself).
Example:
Input: root = 7
/ / \ \
4 2 2 4
/ | / | | \ | \
3 2 6 7 7 6 2 3
Output: true
Explanation: The left side of the tree is a mirror image of the right side
Input: root= 2
/ | \
3 4 3
/ | \
5 6 5
Output: true
Approach: The given problem can be solved by using the preorder traversal. The idea is to pass two root nodes as parameters and check if the value of the current nodes is the same and use recursion to check if the value of children of the left node is the same as the values of children of the right node.
Below steps can be followed to solve the problem:
- Apply pre-order traversal on the N-ary tree:
- Check if the value of both the root nodes is the same or not.
- Also, check if the number of nodes of both the roots is the same or not
- Iterate the children node of the left root from left to right and simultaneously iterate the nodes of the right node from right to left and use recursion.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
class Node
{
public :
vector<Node *> children;
int val;
Node( int v)
{
val = v;
children = {};
}
};
bool preorder(
Node *root1, Node *root2)
{
if (root1->val != root2->val || root1->children.size() != root2->children.size())
return false ;
int size = root1->children.size();
for ( int i = 0; i < (size+1)/2; i++)
{
if (!preorder(
root1->children[i],
root2->children[size - 1 - i]))
return false ;
}
return true ;
}
bool isSymmetric(Node *root)
{
if (root == NULL)
return true ;
return preorder(root, root);
}
int main()
{
Node *seven = new Node(7);
Node *five1 = new Node(5);
Node *five2 = new Node(5);
Node *four = new Node(4);
seven->children.push_back(five1);
seven->children.push_back(four);
seven->children.push_back(five2);
if (isSymmetric(seven))
{
cout << "true" << endl;
}
else
{
cout << "false" << endl;
}
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
public static boolean isSymmetric(Node root)
{
if (root == null )
return true ;
return preorder(root, root);
}
public static boolean preorder(
Node root1, Node root2)
{
if (root1.val != root2.val
|| root1.children.size()
!= root2.children.size())
return false ;
int size = root1.children.size();
for ( int i = 0 ; i < size; i++) {
if (!preorder(
root1.children.get(i),
root2.children.get(size - 1 - i)))
return false ;
}
return true ;
}
public static void main(String[] args)
{
Node seven = new Node( 7 );
Node five1 = new Node( 5 );
Node five2 = new Node( 5 );
Node four = new Node( 4 );
seven.children.add(five1);
seven.children.add(four);
seven.children.add(five2);
System.out.println(
isSymmetric(seven));
}
static class Node {
List<Node> children;
int val;
public Node( int val)
{
this .val = val;
children = new ArrayList<>();
}
}
}
|
Python3
class Node:
def __init__( self , val):
self .val = val
self .children = []
def preorder(root1, root2):
if (root1.val ! = root2.val or len (root1.children) ! = len (root2.children)):
return False
size = len (root1.children)
for i in range ( 0 , (size + 1 ) / / 2 ):
if (preorder(root1.children[i],
root2.children[size - 1 - i]) = = False ):
return False
return True
def isSymmetric(root):
if (root = = None ):
return True
return preorder(root, root)
seven = Node( 7 )
five1 = Node( 5 )
five2 = Node( 5 )
four = Node( 4 )
seven.children.append(five1)
seven.children.append(four)
seven.children.append(five2)
if (isSymmetric(seven)):
print ( "True" )
else :
print ( "False" )
|
C#
using System;
using System.Collections.Generic;
public class GFG {
static bool isSymmetric(Node root)
{
if (root == null )
return true ;
return preorder(root, root);
}
static bool preorder(
Node root1, Node root2)
{
if (root1.val != root2.val
|| root1.children.Count
!= root2.children.Count)
return false ;
int size = root1.children.Count;
for ( int i = 0; i < size; i++) {
if (!preorder(
root1.children[i],
root2.children[size - 1 - i]))
return false ;
}
return true ;
}
public static void Main(String[] args)
{
Node seven = new Node(7);
Node five1 = new Node(5);
Node five2 = new Node(5);
Node four = new Node(4);
seven.children.Add(five1);
seven.children.Add(four);
seven.children.Add(five2);
Console.WriteLine(
isSymmetric(seven));
}
class Node {
public List<Node> children;
public int val;
public Node( int val)
{
this .val = val;
children = new List<Node>();
}
}
}
|
Javascript
<script>
class Node {
constructor(v) {
this .val = v;
this .children = [];
}
};
function preorder(root1, root2) {
if (root1.val != root2.val || root1.children.length != root2.children.length)
return false ;
let size = root1.children.length;
for (let i = 0; i < size; i++) {
if (!preorder(
root1.children[i],
root2.children[size - 1 - i]))
return false ;
}
return true ;
}
function isSymmetric(root) {
if (root == null )
return true ;
return preorder(root, root);
}
let seven = new Node(7);
let five1 = new Node(5);
let five2 = new Node(5);
let four = new Node(4);
seven.children.push(five1);
seven.children.push(four);
seven.children.push(five2);
if (isSymmetric(seven)) {
document.write( "true" );
}
else {
document.write( "false" );
}
</script>
|
Time Complexity: O(N), where N is the number of nodes in the tree
Auxiliary Space: O(H), Where H is the height of the tree