N-ary trees - is it symmetric or not

algorithm, data-structures, tree, tree-traversal

Solution

One way to think about this problem is to notice that a tree is symmetric if it is its own reflection, where the reflection of a tree is defined recursively:

- The reflection of the empty tree is itself.

- The reflection of a tree with root r and children c1, c2, ..., cn is the tree with root r and children reflect(cn), ..., reflect(c2), reflect(c1).

You can then solve this problem by computing the tree's reflection and checking if it's equal to the original tree. This again can be done recursively:

- The empty tree is only equal to itself.

- A tree with root r and children c1, c2, ..., cn is equal to another tree T iff the other tree is nonempty, has root r, has n children, and has children that are equal to c1, ..., cn in that order.

Of course, this is a bit inefficient because it makes a full copy of the tree before doing the comparison. The memory usage is O(n + d), where n is the number of nodes in the tree (to hold the copy) and d is the height of the tree (to hold the stack frames in the recursion tom check for equality). Since d = O(n), this uses O(n) memory. However, it runs in O(n) time since each phase visits each node exactly once.

A more space-efficient way of doing this would be to use the following recursive formulation:

1. The empty tree is symmetric.
2. A tree with n children is symmetric if the first and last children are mirrors, the second and penultimate children are mirrors, etc.

You can then define two trees to be mirrors as follows:

- The empty tree is only a mirror of itself.

- A tree with root r and children c1, c2,..., cn is a mirror of a tree with root t and children d1, d2, ..., dn iff r = t, c1 is a mirror of dn, c2 is a mirror of dn-1, etc.

This approach also runs in linear time, but doesn't make a full copy of the tree. Comsequently, the memory usage is only O(d), where d is the depth of the tree. This is at worst O(n) but is in all likelihood much better.

Problem

Given an N-ary tree, find out if it is symmetric about the line drawn through the root node of the tree. It is easy to do it in case of a binary tree. However for N-ary trees it seems to be difficult

Original source