Given a binary tree, in-place convert it into a doubly-linked list following the spiral order.

The conversion should be done so that the left child pointer of a binary tree node should act as a previous pointer for a doubly-linked list node, and the right child pointer should act as the next pointer for a doubly-linked list node. The conversion should also be done by only exchanging the pointers without allocating any memory for the doubly linked list’s nodes.

 
For example,

Binary Tree to Spiral Doubly Linked List

Practice this problem

1. Using Hashing

We can use hashing to convert the binary tree into a doubly-linked list. The idea is to traverse the tree in a preorder fashion and store each node and its level number in a map using the level number as a key. Finally, iterate through the map and push each level node into the doubly linked list in spiral order.

This approach is demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Output:

1 —> 2 —> 3 —> 7 —> 6 —> 5 —> 4 —> nullptr

Java


Download  Run Code

Output:

1 —> 2 —> 3 —> 7 —> 6 —> 5 —> 4 —> null

Python


Download  Run Code

Output:

1 —> 2 —> 3 —> 7 —> 6 —> 5 —> 4 —> None

The time complexity of the above solution is O(n), where n is the total number of nodes in the binary tree. The auxiliary space required by the program is O(n) for map and call stack.

2. By Traversing the Tree in Spiral Order

We can also perform spiral order traversal of the binary tree using deque (Double-ended queue), similar to the standard level order traversal. However, odd level nodes are processed from left to right, and even level nodes are processed from right to left. The deque is used to facilitate traversal in both directions.

Now to convert the binary tree into a doubly-linked list, store all nodes that were popped from the deque during spiral order traversal and later insert those nodes into the doubly linked list in the correct order. This is demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Output:

1 —> 2 —> 3 —> 7 —> 6 —> 5 —> 4 —> nullptr

Java


Download  Run Code

Output:

1 —> 2 —> 3 —> 7 —> 6 —> 5 —> 4 —> null

Python


Download  Run Code

Output:

1 —> 2 —> 3 —> 7 —> 6 —> 5 —> 4 —> None

The time complexity of the above approach is O(n), where n is the total number of nodes in the binary tree. It uses O(n) extra space for the stack.