Javatpoint Logo
Javatpoint Logo

Q. Program to create a doubly linked list from a Ternary Tree.

Explanation

In this program, The given ternary tree will be converted into a corresponding doubly linked list.

The ternary tree is a hierarchical data structure in which each node can have at most three children. This can be accomplished by traversing the ternary tree in a preorder fashion that is, root -> left child -> middle child -> right child. First, traverse root node and add it to the list. Then, add its left, middle and right subtrees respectively.

Ternary tree:

Program to create a doubly linked list from a Ternary Tree

Corresponding doubly linked list:

Program to create a doubly linked list from a Ternary Tree

Algorithm

  1. Define a Node class which represents a node in the ternary tree. It will have four properties: data, left, middle, right where left, middle and right represent three children of a node.
  2. Root will represent the root of the ternary tree. Head and tail node represent the head and tail of the doubly linked list.
  3. convertTernaryToDLL() will convert the given ternary tree to corresponding doubly linked list.
    1. Nodes left, middle and right represent the child of given node.
    2. If the node is not null, then the node will be inserted into the list.
    3. If the list is empty, both head and tail will point to a node.
    4. If the list is not empty then, the node will be inserted at the end of the list. Here, pointer left, and right will represent the previous and next pointer of the doubly linked list. The middle will not point to anything hence, simply set it to null.
    5. When a node is successfully added into the list then, call convertTernaryToDLL() recursively to add a left, middle and right child of given node to the list.
  4. displayDLL() will show all the nodes present in the list.
    1. Define a new node 'current' that will point to the head.
    2. Print current.data till current points to null.
    3. Current will point to the next node in the list in each iteration.

Solution

Python

Output:

Nodes of the generated doubly linked list: 

5 10 20 40 50 12 24 36 48 15 30 45 60 

C

Output:

Nodes of generated doubly linked list: 
5 10 20 40 50 12 24 36 48 15 30 45 60 

JAVA

Output:

Nodes of generated doubly linked list: 
5 10 20 40 50 12 24 36 48 15 30 45 60 

C#

Output:

Nodes of generated doubly linked list: 
5 10 20 40 50 12 24 36 48 15 30 45 60 

PHP

Output:

Nodes of generated doubly linked list: 
5 10 20 40 50 12 24 36 48 15 30 45 60 

Next Topic#




Please Share

facebook twitter google plus pinterest

B.Tech / MCA


Learn Latest Tutorials