Вы находитесь на странице: 1из 5

Converting a Tree to a Doubly Linked List « RawKam (beta) http://www.rawkam.com/?

p=1139

« 5 Pirates dividing 100 coins Home knapsack Problem »

Converting a Tree to a Doubly Linked List


BY KAMAL, ON AUGUST 24TH, 2010

Write a function which will accept a Binary Search Tree and convert it to a sorted Doubly linked List. For Example: If we have a
Binary Search Tree as shown below

Then the corresponding Doubly Linked List will be the Inorder traversal of the above tree

The Node of a Tree has a data and two pointers which points to the left and right subtrees

The Node of a Doubly Linked List has a data and two pointers which point to the previous and next node

If you notice the structure of above two nodes is exactly the same (except for the nomenclature of pointers, which is immaterial). The
Structure is as below:

1 struct Node{
2 int data;
3 struct Node *left;
4 struct Node *right;
5 }

I have named the two pointers as left and right, but they can be named pre/next or anything.

If we are codding in C++, then we can take the advantage of Object Oriented Programming and define the Node as a Class, The
benefit we will get is that we can also define the constructor and/or other operations, like below, I have also defined a constructor
which initializes the pointers to NULL in the member initialization list of constructor:

01 /** Node of Tree and Doubly Linked list are same.


02 * Both have one data field and two pointers.
03 * In Doubly List the pointers points to prev and next node.
04 * In Tree the pointers points to left and right subtree.
05 */
06 class Node{
07 public:

1 of 5 12/4/2010 7:15 PM
Converting a Tree to a Doubly Linked List « RawKam (beta) http://www.rawkam.com/?p=1139

08 int data;
09 Node* left;
10 Node* right;
11
12 // Constructor
13 Node(int v):data(v), left(NULL), right(NULL){; }
14 };

A better example of how to declare a Node is shown in this post.

Solution:

Since the structure of Nodes is same in both the cases, the conversion of BST (Binary Search Tree) to Doubly Linked List will
only require rearrangement of pointers. We use recursive algorithm to convert Tree to Doubly linked list

Algorithm:

If tree is not empty

Convert left subtree to List, let hLeft points to it


Convert right subtree to List, let hRight points to it
Append hLeft with root and then hRight

Code:

The Recursive function to convert will be as shown below:

01 /** Recursively convert a Binary Tree to a Doubly Linked List


02 */
03 Node* treeToList(Node* r) {
04
05 // Terminating Condition of Recursion
06 if (r == NULL){ return NULL; }
07
08 // Convert to list the left and right subtrees recursively
09 Node *prev = treeToList(r‐>left);
10 Node *next = treeToList(r‐>right);
11
12 // Making the root Node a separate list
13 r‐>left = NULL;
14 r‐>right = NULL;
15
16 /* Append everything together in sorted order */
17 prev = append(prev, r);
18 prev = append(prev, next);
19
20 return(prev);
21 }

The above function uses function append which will be as shown below:

01 /** Given two doubly linked lists,


02 * This function will append them and return the new list.
03 */
04 Node* append(Node *a, Node *b) {
05
06 // If any of the two lists is null return the 2nd list.
07 if (a == NULL) return b;
08 if (b == NULL) return a;
09
10 Node* head = a;
11
12 while(a‐>right != NULL){ a = a‐>right; }
13
14 a‐>right = b;
15 b‐>left = a;
16
17 return(head);
18 }

2 of 5 12/4/2010 7:15 PM
Converting a Tree to a Doubly Linked List « RawKam (beta) http://www.rawkam.com/?p=1139

Time Complexity: O(n). Because each node is visited only once .

Please let me know your Feedback, Suggestions and Comments

References: http://cslibrary.stanford.edu/109/TreeListRecursion.html

—————————————-

For a change let me writing the entire program for your Convenience below :

001 #include <iostream>


002 using namespace std;
003
004 /** Node of Tree and Doubly Linked list are same.
005 * Both have one data field and two pointers.
006 * In Doubly List the pointers points to prev and next node.
007 * In Tree the pointers points to left and right subtree.
008 */
009 class Node{
010 public:
011 int data;
012 Node* left;
013 Node* right;
014
015 // Constructor
016 Node(int v):data(v), left(NULL), right(NULL){; }
017 };
018
019 /** Helper function to create a sample tree. Used to debug the program.
020 * It create the below tree and returns a pointer to the root.
021 *
022 * 4
023 * / \
024 * 2 5
025 * / \
026 * 1 3
027 */
028 Node * createSampleTree(){
029 Node *r = NULL;
030 r = new Node(4);
031
032 r‐>left = new Node(2);
033 r‐>left‐>left = new Node(1);
034 r‐>left‐>right = new Node(3);
035
036 r‐>right = new Node(5);
037
038 return r;
039 }
040
041 /** Prints the in Inorder Tracersal of the tree pointed to by r.
042 */
043 void printInorder(Node* r){
044 if(!r){ return; }
045
046 printInorder(r‐>left);
047 cout<<" "<<r‐>data;
048 printInorder(r‐>right);
049 }
050
051 /** Prints the Doubly link list whose head is at h linearly.
052 */
053 void printDoublyList(Node* h){
054
055 while(h){
056 cout<<" "<<h‐>data;
057 h = h‐>right;
058 }
059 cout<<endl;
060 }
061
062 /** Given two doubly linked lists,
063 * This function will append them and return the new list.

3 of 5 12/4/2010 7:15 PM
Converting a Tree to a Doubly Linked List « RawKam (beta) http://www.rawkam.com/?p=1139

064 */
065 Node* append(Node *a, Node *b) {
066
067 // If any of the two lists is null return the 2nd list.
068 if (a == NULL) return b;
069 if (b == NULL) return a;
070
071 Node* head = a;
072
073 while(a‐>right != NULL){ a = a‐>right; }
074
075 a‐>right = b;
076 b‐>left = a;
077
078 return(head);
079 }
080
081 /** Recursively convert a Binary Tree to a Doubly Linked List
082 */
083 Node* treeToList(Node* r) {
084
085 // Terminating Condition of Recursion
086 if (r == NULL){ return NULL; }
087
088 // Convert to list the left and right subtrees recursively
089 Node *prev = treeToList(r‐>left);
090 Node *next = treeToList(r‐>right);
091
092 // Making the root Node a separate list
093 r‐>left = NULL;
094 r‐>right = NULL;
095
096 /* Append everything together in sorted order */
097 prev = append(prev, r);
098 prev = append(prev, next);
099
100 return(prev);
101 }
102
103 int main()
104 {
105 Node* root = createSampleTree();
106 cout<<"In order Tracersal :";
107 printInorder(root);
108
109 root = treeToList(root);
110 cout<<"\nList :";
111 printDoublyList(root);
112
113 getchar();
114 return 0;
115 }

Output:

Subscribe to this author's posts feed via RSS


ALGORIT HMS, LINKED LIS T , T REES ADOBE, ADOBE INT ERVIEW QUEST IONS, ALGORIT HM, BINARY SEARCH
T REE, BST T O DOUBLY LINKED LIST , BST T O LINKED LIST , CONVERT ING BINARY S EARCH T REE T O DOUBLY
LINKED LIST , CONVERT ING T REE T O DOUBLY LINKED LIST , DOUBLY LINKED LIS T , DOUBLY LINKED LIST
QUEST IONS , GOOGLE, HCL, INT ERVIE W, INT ERVIEW QUEST ION, INT ERVIE W QUEST IONS, LINKED LIST QUEST IONS,
MICROSOFT , MICROSOFT INT E RVIEW QUEST IONS , T ECHNICAL INT ERVIEW QUE ST IONS, T ECHNICAL QUEST IONS,
T ECHNICAL T EST , T REE INT ERVIE W QUEST IONS, T REE QUES T IONS (NO RAT INGS YET )

« 5 Pirates dividing 100 coins Home knapsack Problem »

4 of 5 12/4/2010 7:15 PM
Converting a Tree to a Doubly Linked List « RawKam (beta) http://www.rawkam.com/?p=1139

You must be logged in to post a comment.

« 5 Pirates dividing 100 coins Home knapsack Problem »

5 of 5 12/4/2010 7:15 PM

Вам также может понравиться