Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a binary search tree into a doubly linked list?

Given a binary search tree, i need to convert it into a doubly linked list(by traversing in zig zag order) using only pointers to structures in C++ as follows,

Given Tree:

                1
                |
        +-------+---------+
        |                 |
        2                 3
        |                 |
   +----+---+        +----+---+
   |        |        |        |
   4        5        6        7
   |        |        |        |
+--+--+  +--+--+  +--+--+  +--+--+
|     |  |     |  |     |  |     |
8     9  10    11 12    13 14    15

Node Structure:

struct node
{
    char * data;
    node * left;
    node * right;
};

Create List(zig zag order):

1 <-> 3 <-> 2 <-> 4 <-> 5 <-> 6 <-> 7 <-> 15 <-> ... <-> 8

Could someone please help me out.

like image 312
josh Avatar asked Sep 18 '10 17:09

josh


People also ask

How do you convert a binary tree to a doubly linked list?

The binary tree is a tree data structure in which each node has at most two children node. This can be achieved by traversing the tree in the in-order manner that is, left the child -> root ->right node. Traverse left sub-tree and convert it into the doubly linked list by adding nodes to the end of the list.

How do you convert a binary tree to a linked list?

Given a binary tree, flatten it into linked list in-place. Usage of auxiliary data structure is not allowed. After flattening, left of each node should point to NULL and right should contain next node in preorder. Simple Approach: A simple solution is to use Level Order Traversal using Queue.

Can you binary search a doubly linked list?

It's technically correct to say that the runtime of binary search on a doubly-linked list is O(n log n), but that's not a tight upper bound. Using a slightly better implementation of binary search and a more clever analysis, it's possible to get binary search to run in time O(n).

Can we implement binary tree using doubly linked list?

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.


1 Answers

This is a Breadth-first search algorithm. Wikipedia has a good explanation on how to implement it.

After implementing the algorithm, creating your linked list should be a no-brainer (since it will only be a matter of appending each visited element to the list)

like image 112
Edison Gustavo Muenz Avatar answered Oct 19 '22 04:10

Edison Gustavo Muenz