VOOZH about

URL: https://www.geeksforgeeks.org/dsa/convert-binary-tree-to-doubly-linked-list-by-keeping-track-of-visited-node/

⇱ Convert Binary Tree to Doubly Linked List by keeping track of visited node - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Convert Binary Tree to Doubly Linked List by keeping track of visited node

Last Updated : 23 Jul, 2025

Given a Binary Tree, The task is to convert it to a Doubly Linked List keeping the same order. 

  • The left and right pointers in nodes are to be used as previous and next pointers respectively in converted DLL. 
  • The order of nodes in DLL must be the same as in Inorder for the given Binary Tree
  • The first node of Inorder traversal (leftmost node in BT) must be the head node of the DLL. 

👁 TreeToList

The following two different solutions have been discussed for this problem. 
Convert a given Binary Tree to a Doubly Linked List | Set 1
Convert a given Binary Tree to a Doubly Linked List | Set 2

Approach: Below is the idea to solve the problem:

The idea is to do in-order traversal of the binary tree. While doing inorder traversal, keep track of the previously visited node in a variable, say prev. For every visited node, make it next to the prev and set previous of this node as prev.

Below is the implementation of the above approach:


Output
25 12 30 10 36 15 

Note: The use of static variables like above is not a recommended practice, here static is used for simplicity. Imagine if the same function is called for two or more trees. The old value of prev would be used in the next call for a different tree. To avoid such problems, we can use a double-pointer or a reference to a pointer.

Time Complexity: O(N), The above program does a simple inorder traversal, so time complexity is O(N) where N is the number of nodes in a given Binary tree.
Auxiliary Space: O(N), For recursion call stack.

Convert a given Binary Tree to Doubly Linked List iteratively using Stack data structure:

Do iterative inorder traversal and maintain a prev pointer to point the last visited node then point current node's perv to prev and prev's next to current node. 

Below is the implementation of the above approach:


Output
25 12 30 10 36 15 

Time complexity: O(N)
Auxiliary Space: O(N)

Convert a given Binary Tree to Doubly Linked List iteratively using Morris Traversal:

The idea is to keep track of previous node while doing Inorder tree traversal using Morris Traversal. This removes the need for a recursion call stack or a stack thus reducing space complexity


Output
25 12 30 10 36 15 

Time complexity: O(N)

Auxiliary Space: O(1)

Comment