VOOZH about

URL: https://www.geeksforgeeks.org/dsa/create-doubly-linked-list-ternary-ree/

⇱ Create a Doubly Linked List from a Ternary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Create a Doubly Linked List from a Ternary Tree

Last Updated : 1 Jul, 2022

Given a ternary tree, create a doubly linked list out of it. A ternary tree is just like a binary tree but instead of having two nodes, it has three nodes i.e. left, middle, and right.

The doubly linked list should hold the following properties –  

  1. The left pointer of the ternary tree should act as prev pointer of the doubly linked list.
  2. The middle pointer of the ternary tree should not point to anything.
  3. Right pointer of the ternary tree should act as the next pointer of the doubly linked list.
  4. Each node of the ternary tree is inserted into the doubly linked list before its subtrees and for any node, its left child will be inserted first, followed by the mid and right child (if any).

For the above example, the linked list formed for below tree should be NULL <- 30 <-> 5 <-> 1 <-> 4 <-> 8 <-> 11 <-> 6 <-> 7 <-> 15 <-> 63 <-> 31 <-> 55 <-> 65 -> NULL 

👁 tree

We strongly recommend you to minimize your browser and try this yourself first.

The idea is to traverse the tree in a preorder fashion similar to binary tree preorder traversal. Here, when we visit a node, we will insert it into a doubly linked list, in the end, using a tail pointer. That we use to maintain the required insertion order. We then recursively call for left child, middle child and right child in that order.

Below is the implementation of this idea. 


Output
Created Double Linked list is:
30 5 1 4 8 11 6 7 15 63 31 55 65 

Time Complexity: O(n), as we are using recursion to traverse n times. Where n is the number of nodes in the tree.
Auxiliary Space: O(n), as we are using extra space for the linked list.

Comment
Article Tags: