Given a binary tree, in-place convert it into a doubly linked list.

The conversion should be done such that the left and right pointers of binary tree nodes should act as previous and next pointers in a doubly-linked list, and the doubly linked list nodes should follow the same order of nodes as inorder traversal on the tree.

 
For example,

Convert Binary Tree into Doubly Linked List

Practice this problem

1. Using Inorder Traversal

The idea is to perform an inorder traversal on the tree, and for every node encountered, insert it at the beginning of a doubly linked list. Since we are inserting nodes at the beginning of the doubly linked list, reverse the linked list to follow the same order of nodes as in the inorder traversal.

Following is the implementation in C++, Java, and Python based on the above idea:

C++


Download  Run Code

Output:

4 2 5 1 6 3 7

Java


Download  Run Code

Output:

4 2 5 1 6 3 7

Python


Download  Run Code

Output:

4 2 5 1 6 3 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.

2. Using Reverse Inorder Traversal

The above approach requires two passes – one pass for converting a binary tree into a doubly linked list and one pass to reverse the DDL. We can solve this problem in a single traversal of the tree using reverse inorder traversal instead of normal inorder traversal. In reverse inorder traversal, we process the right subtree before the left subtree. Now, the nodes will follow the order of inorder traversal.

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

C++


Download  Run Code

Output:

4 2 5 1 6 3 7

Java


Download  Run Code

Output:

4 2 5 1 6 3 7

Python


Download  Run Code

Output:

4 2 5 1 6 3 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.

3. Keeping track of previously processed node in the inorder traversal

We can solve this problem in a single traversal by doing inorder traversal only. The idea is to keep track of the previously processed node in the inorder traversal, and for every encountered node, set its left child to prev and prev’s right child to the current node.

Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Output:

4 2 5 1 6 3 7

Java


Download  Run Code

Output:

4 2 5 1 6 3 7

Python


Download  Run Code

Output:

4 2 5 1 6 3 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.