VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-given-generic-n-ary-tree-is-symmetric-horizontally/

⇱ Check if given Generic N-ary Tree is Symmetric horizontally - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if given Generic N-ary Tree is Symmetric horizontally

Last Updated : 23 Jul, 2025

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:


Output
true

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 

Comment