Given a ternary tree, in-place convert it into a doubly-linked list. A ternary tree is a tree data structure in which each node has three child nodes distinguished as left, mid, and right.

The conversion should be done so that the left child pointer of a ternary tree node should act as a previous pointer for the doubly linked list node, the right child pointer should serve as the next pointer for the doubly linked list node, and the mid-child pointer should point to nothing. The conversion should be done by only exchanging ternary tree node pointers without allocating any extra memory for the nodes of the doubly linked list.

 
Consider the following ternary tree, which shows the order in which the nodes should be present in a doubly-linked list:

Input: Ternary Tree
 
            1
          / | \
        /   |   \
      /     |     \
     2      9      12
   / | \   / \     |  \
  3  6  8 10  11   13  16
  |   \           / \  |
  4    7         14 15 17
   \
    5
 
Output: Doubly Linked List
 
1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> 9 —> 10 —> 11 —> 12 —> 13 —> 14 —> 15 —> 16 —> 17 —> nullptr

As evident from the above example, the ternary tree’s root node is pushed before its children into the doubly linked list. Every node recursively follows this in the subtree rooted at its left child, mid-child, and right child, in that order.

Practice this problem

The idea is to perform reverse postorder traversal on a ternary tree. In reverse postorder traversal, before processing a ternary tree node, its right child is processed first, followed by its mid and left child. After traversing all children of a ternary tree node, insert the node at the front of the doubly linked list. The reverse postorder traversal is used to ensure the correct insertion order in a doubly-linked list.

Following is the C++, Java, and Python program that demonstrates the idea:

C++


Download  Run Code

Output:

1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> 9 —> 10 —> 11 —> 12 —> 13 —> 14 —> 15 —> 16 —> 17 —> nullptr

Java


Download  Run Code

Output:

1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> 9 —> 10 —> 11 —> 12 —> 13 —> 14 —> 15 —> 16 —> 17 —> null

Python


Download  Run Code

Output:

1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> 8 —> 9 —> 10 —> 11 —> 12 —> 13 —> 14 —> 15 —> 16 —> 17 —> None

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