VOOZH about

URL: https://www.geeksforgeeks.org/dsa/convert-a-binary-tree-into-doubly-linked-list-in-spiral-fashion/

⇱ Convert a Binary Tree into Doubly Linked List in spiral fashion - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Convert a Binary Tree into Doubly Linked List in spiral fashion

Last Updated : 23 Jul, 2025

Given a binary tree, convert it into a doubly linked list (DLL) where the nodes are arranged in a spiral order. The left pointer of the binary tree node should act as the previous node in the DLL, and the right pointer should act as the next node in the DLL.

The solution should not allocate extra memory for the DLL nodes. It should use the existing binary tree nodes for creating the DLL, meaning only changes to the pointers are allowed.

Example:

Input:

👁 Convert-a-Binary-Tree-into-Doubly-Linked-List-in-spiral-fashion

Output:

👁 Convert-a-Binary-Tree-into-Doubly-Linked-List-in-spiral-fashion-2


Explanation: The above binary tree is converted into doubly linked list where left pointer of the binary tree node act as the previous node and right pointer of the binary tree node act as the next node.

Approach:

The idea is to use a deque (double-ended queue) that can be expanded or contracted from both ends (either from its front or its back). We perform a level-order traversal, but to maintain spiral order, for every odd level, we dequeue a node from the front and insert its left and right children at the back of the deque. For each even level, we dequeue a node from the back and insert its right and left children at the front of the deque.

We also maintain a stack to store the binary tree nodes. Whenever we pop nodes from the deque, we push that node into the stack. Later, we pop all the nodes from the stack and insert them at the beginning of the list.

Below is the implementation of the above approach:


Output
1 3 2 4 5 6 7 

Time Complexity: O(n), as we are using a loop to traverse n times.
Auxiliary Space: O(n), as we are using extra space for dequeue and stack.

Related articles:

Comment
Article Tags: