Javatpoint Logo
Javatpoint Logo

1. Python program to convert a given binary tree to doubly linked list.

In this program, we need to convert the given binary tree to corresponding doubly liked list.

The binary tree is a tree data structure in which each node has at most two children node.

This can be achieved by traversing the tree in the in-order manner that is, left the child -> root ->right node. Traverse left sub-tree and convert it into the doubly linked list by adding nodes to the end of the list. In this way, the leftmost node will become head of the list. Then, convert the right sub-tree into the doubly linked list.

Python program to convert a given binary tree to doubly linked list Python program to convert a given binary tree to doubly linked list

ALGORITHM:

  1. Define a Node class which represents a node in the binary tree. It will have three properties: data left, and right where the left and right represent two children of a node.
  2. Root will represent the root of the binary tree. Head and tail node represent the head and tail of the doubly linked list.
  3. BinaryTreeToDLL() will convert the given binary tree to the corresponding doubly linked list.
  • Perform inorder traversal of the binary tree by converting the left subtree first.
  • If the list is empty, both head and tail will point to a node.
  • If the list is not empty, 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.
  • Now, recursively call BinaryTreeToDLL() to convert the right subtree.

a. display() will show all the nodes present in the list.

  • Define a new node 'current' that will point to the head.
  • Print current.data till current points to null.
  • Current will point to the next node in the list in each iteration.

PROGRAM:

Output:

Nodes of generated doubly linked list: 
4 2 5 1 6 3 7 
Next TopicPython Programs





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA