Given an m–ary tree, write an efficient algorithm to convert the tree into its mirror.

An m-ary tree (aka k–ary tree) is a tree in which each node has no more than m children. Each node of an m–ary tree has an array for storing pointers to each of its children.

The binary tree and the ternary tree are special cases of the m–ary tree where m = 2 and m = 3. Consider the following diagram, which displays an m–ary tree with m = 5:

M–ary Tree

The following m–ary tree is a mirror image of the above tree:

M–ary Tree Mirror

 
Related Post:

Convert a binary tree to its mirror

 
The idea is similar to the above post – Traverse the tree in a postorder fashion and for every node, first recursively convert its children to mirror, and then reverse the array storing pointers to each of its children. The preorder traversal would also work here.

Traversing an m–ary tree is very similar to binary tree traversal. The postorder traversal on a binary tree visits the left subtree first, followed by the right subtree, and the parent node is processed at last. Since there are m children per node in an m–ary tree, the postorder traversal visits the 1st child first, followed by the 2nd child, …, all the way till the m’th child. After processing all children, processes the parent node.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

1 6 14 13 20 19 18 17 5 4 12 11 10 3 2 9 8 16 15 7

Java


Download  Run Code

Output:

1 6 14 13 20 19 18 17 5 4 12 11 10 3 2 9 8 16 15 7

Python


Download  Run Code

Output:

1 6 14 13 20 19 18 17 5 4 12 11 10 3 2 9 8 16 15 7

The time complexity of the above solution is O(n), where n is the total number of nodes in the binary tree. The program requires O(h) extra space for the call stack, where h is the height of the tree.