Convert a Binary Tree into Doubly Linked List in spiral fashion

3.4

Given a Binary Tree, convert it into Doubly Linked List where the nodes are represented Spirally. The left pointer of the binary tree node should act as a previous node for created DLL and right pointer should act as next node.

The solution should not allocate extra memory for DLL nodes. It should use binary tree nodes for creating DLL i.e. only change of pointers is allowed
image(5)

For example, for the tree on left side, Doubly Linked List can be,

1 2 3 7 6 5 4 8 9 10 11 13 14 or

1 3 2 4 5 6 7 14 13 11 10 9 8.

 

We strongly recommend you to minimize your browser and try this yourself first.

We can do this by doing a spiral order traversal in O(n) time and O(n) extra space. The idea is to use deque (Double-ended queue) that can be expanded or contracted on both ends (either its front or its back). We do something similar to level order traversal but to maintain spiral order, for every odd level, we dequeue node from the front and inserts its left and right children in the back of the deque data structure. And for each even level, we dequeue node from the back and inserts its right and left children in the front of deque. We also maintain a stack to store Binary Tree nodes. Whenever we pop nodes from deque, we push that node into stack. Later, we pop all nodes from stack and push the nodes in the beginning of the list. We can avoid use of stack if we maintain a tail pointer that always points to last node of DLL and inserts nodes in O(1) time in the end.

Below is C++ implementation of above idea

C++

/* c++ program to convert Binary Tree into Doubly
   Linked List where the nodes are represented
   spirally. */
#include <bits/stdc++.h>
using namespace std;

// A Binary Tree Node
struct Node
{
    int data;
    struct Node *left, *right;
};

/* Given a reference to the head of a list and a node,
inserts the node on the front of the list. */
void push(Node** head_ref, Node* node)
{
    // Make right of given node as head and left as
    // NULL
    node->right = (*head_ref);
    node->left = NULL;

    // change left of head node to given node
    if ((*head_ref) !=  NULL)
        (*head_ref)->left = node ;

    // move the head to point to the given node
    (*head_ref) = node;
}

// Function to prints contents of DLL
void printList(Node *node)
{
    while (node != NULL)
    {
        cout << node->data << " ";
        node = node->right;
    }
}

/* Function to print corner node at each level */
void spiralLevelOrder(Node *root)
{
    // Base Case
    if (root == NULL)
        return;

    // Create an empty deque for doing spiral
    // level order traversal and enqueue root
    deque<Node*> q;
    q.push_front(root);

    // create a stack to store Binary Tree nodes
    // to insert into DLL later
    stack<Node*> stk;

    int level = 0;
    while (!q.empty())
    {
        // nodeCount indicates number of Nodes
        // at current level.
        int nodeCount = q.size();

        // Dequeue all Nodes of current level and
        // Enqueue all Nodes of next level
        if (level&1)    //odd level
        {
            while (nodeCount > 0)
            {
                // dequeue node from front & push it to
                // stack
                Node *node = q.front();
                q.pop_front();
                stk.push(node);

                // insert its left and right children
                // in the back of the deque
                if (node->left != NULL)
                    q.push_back(node->left);
                if (node->right != NULL)
                    q.push_back(node->right);

                nodeCount--;
            }
        }
        else      //even level
        {
            while (nodeCount > 0)
            {
                // dequeue node from the back & push it
                // to stack
                Node *node = q.back();
                q.pop_back();
                stk.push(node);

                // inserts its right and left children
                // in the front of the deque
                if (node->right != NULL)
                    q.push_front(node->right);
                if (node->left != NULL)
                    q.push_front(node->left);
                nodeCount--;
            }
        }
        level++;
    }

    // head pointer for DLL
    Node* head = NULL;

    // pop all nodes from stack and
    // push them in the beginning of the list
    while (!stk.empty())
    {
        push(&head, stk.top());
        stk.pop();
    }

    cout << "Created DLL is:\n";
    printList(head);
}

// Utility function to create a new tree Node
Node* newNode(int data)
{
    Node *temp = new Node;
    temp->data = data;
    temp->left = temp->right = NULL;

    return temp;
}

// Driver program to test above functions
int main()
{
    // Let us create binary tree shown in above diagram
    Node *root =  newNode(1);
    root->left = newNode(2);
    root->right = newNode(3);
    root->left->left = newNode(4);
    root->left->right = newNode(5);
    root->right->left = newNode(6);
    root->right->right = newNode(7);

    root->left->left->left  = newNode(8);
    root->left->left->right  = newNode(9);
    root->left->right->left  = newNode(10);
    root->left->right->right  = newNode(11);
    //root->right->left->left  = newNode(12);
    root->right->left->right  = newNode(13);
    root->right->right->left  = newNode(14);
    //root->right->right->right  = newNode(15);

    spiralLevelOrder(root);

    return 0;
}

Java

/* Java program to convert Binary Tree into Doubly Linked List 
   where the nodes are represented spirally */

import java.util.*;

// A binary tree node
class Node 
{
    int data;
    Node left, right;

    public Node(int data) 
    {
        this.data = data;
        left = right = null;
    }
}

class BinaryTree 
{
    Node root;
    Node head;

    /* Given a reference to a node,
       inserts the node on the front of the list. */
    void push(Node node) 
    {
        // Make right of given node as head and left as
        // NULL
        node.right = head;
        node.left = null;

        // change left of head node to given node
        if (head != null) 
            head.left = node;
            
        // move the head to point to the given node
        head = node;
    }

    // Function to prints contents of DLL
    void printList(Node node) 
    {
        while (node != null) 
        {
            System.out.print(node.data + " ");
            node = node.right;
        }
    }

    /* Function to print corner node at each level */
    void spiralLevelOrder(Node root) 
    {
        // Base Case
        if (root == null)
            return;

        // Create an empty deque for doing spiral
        // level order traversal and enqueue root
        Deque<Node> q = new LinkedList<Node>();
        q.addFirst(root);

        // create a stack to store Binary Tree nodes
        // to insert into DLL later
        Stack<Node> stk = new Stack<Node>();

        int level = 0;
        while (!q.isEmpty()) 
        {
            // nodeCount indicates number of Nodes
            // at current level.
            int nodeCount = q.size();

            // Dequeue all Nodes of current level and
            // Enqueue all Nodes of next level
            if ((level & 1) %2 != 0) //odd level
            {
                while (nodeCount > 0) 
                {
                    // dequeue node from front & push it to
                    // stack
                    Node node = q.peekFirst();
                    q.pollFirst();
                    stk.push(node);

                    // insert its left and right children
                    // in the back of the deque
                    if (node.left != null)
                        q.addLast(node.left);
                    if (node.right != null)
                        q.addLast(node.right);

                    nodeCount--;
                }
            } 
            else //even level
            {
                while (nodeCount > 0) 
                {
                    // dequeue node from the back & push it
                    // to stack
                    Node node = q.peekLast();
                    q.pollLast();
                    stk.push(node);

                    // inserts its right and left children
                    // in the front of the deque
                    if (node.right != null)
                        q.addFirst(node.right);
                    if (node.left != null)
                        q.addFirst(node.left);
                    nodeCount--;
                }
            }
            level++;
        }

        // pop all nodes from stack and
        // push them in the beginning of the list
        while (!stk.empty()) 
        {
            push(stk.peek());
            stk.pop();
        }

        System.out.println("Created DLL is : ");
        printList(head);
    }

    // Driver program to test above functions
    public static void main(String[] args) 
    {
        // Let us create binary tree as shown in above diagram
        BinaryTree tree = new BinaryTree();
        tree.root = new Node(1);
        tree.root.left = new Node(2);
        tree.root.right = new Node(3);
        tree.root.left.left = new Node(4);
        tree.root.left.right = new Node(5);
        tree.root.right.left = new Node(6);
        tree.root.right.right = new Node(7);

        tree.root.left.left.left = new Node(8);
        tree.root.left.left.right = new Node(9);
        tree.root.left.right.left = new Node(10);
        tree.root.left.right.right = new Node(11);
        // tree.root.right.left.left = new Node(12);
        tree.root.right.left.right = new Node(13);
        tree.root.right.right.left = new Node(14);
        // tree.root.right.right.right = new Node(15);

        tree.spiralLevelOrder(tree.root);
    }
}

// This code has been contributed by Mayank Jaiswal(mayank_24)


Output :
Created DLL is:
1 2 3 7 6 5 4 8 9 10 11 13 14 

This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

GATE CS Corner    Company Wise Coding Practice

Recommended Posts:



3.4 Average Difficulty : 3.4/5.0
Based on 19 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.