Binary Search Tree to Double Linked List and Vice Versa - Java
1. Ordered Binary Tree
In the ordered binary tree, each node contains a single data element and "small" and "large" pointers to sub-trees (sometimes the two pointers are just called "left" and "right"). Here's an ordered binary tree of the numbers 1 through 5...Figure-1 -- ordered binary tree
2. Circular Doubly Linked List
Here's a circular doubly linked list of the numbers 1 through 5...Figure-2 -- doubly linked circular list
- "Doubly linked" means that each node has two pointers -- the usual "next" pointer that points to the next node in the list and a "previous" pointer to the previous node.
- "Circular" means that the list does not terminate at the first and last nodes. Instead, the "next" from the last node wraps around to the first node. Likewise, the "previous" from the first node wraps around to the last node.
Figure-3 -- a length-1 circular doubly linked list
The Trick -- Separated at Birth?
Here's the trick that underlies the Great Tree-List Problem: look at the nodes that make up the ordered binary tree. Now look at the nodes that make up the linked list. The nodes have the same type structure -- they each contain an element and two pointers. The only difference is that in the tree, the two pointers are labeled "small" and "large" while in the list they are labeled "previous" and "next". Ignoring the labeling, the two node types are the same.3. The Challenge
The challenge is to take an ordered binary tree and rearrange the internal pointers to make a circular doubly linked list out of it. The "small" pointer should play the role of "previous" and the "large" pointer should play the role of "next". The list should be arranged so that the nodes are in increasing order...Figure-4 -- original tree with list "next" arrows added
Complete Drawing
Figure-5 -- original tree with "next" and "previous" list arrows added
4. Problem Statement
Here's the formal problem statement: Write a recursive function treeToList(Node root) that takes an ordered binary tree and rearranges the internal pointers to make a circular doubly linked list out of the tree nodes. The "previous" pointers should be stored in the "small" field and the "next" pointers should be stored in the "large" field. The list should be arranged so that the nodes are in increasing order. Return the head pointer to the new list. The operation can be done in O(n) time -- essentially operating on each node once. Basically take figure-1 as input and rearrange the pointers to make figure-2.Try the problem directly, or see the hints below.Hints
Hint #1
The recursion is key. Trust that the recursive call on each sub-tree works and concentrate on assembling the outputs of the recursive calls to build the result. It's too complex to delve into how each recursive call is going to work -- trust that it did work and assemble the answer from there.Hint #2
The recursion will go down the tree, recursively changing the small and large sub-trees into lists, and then append those lists together with the parent node to make larger lists. Separate out a utility function append(Node a, Node b) that takes two circular doubly linked lists and appends them together to make one list which is returned. Writing a separate utility function helps move some of the complexity out of the recursive function.5. Lessons and Solution Code
The solution code is given below in Java. The most important method is treeToList() and the helper methods join() and append(). Here are the lessons I see in the two solutions...- Trust that the recursive calls return correct output when fed correct input -- make the leap of faith. Look at the partial results that the recursive calls give you, and construct the full result from them. If you try to step into the recursive calls to think how they are working, you'll go crazy.
- Decomposing out well defined helper functions is a good idea. Writing the list-append code separately helps you concentrate on the recursion which is complex enough on its own.
Code:
package ds.trees;
/*
This is the simple Node class from which the tree and list
are built. This does not have any methods -- it's just used
as dumb storage by TreeList.
The code below tries to be clear where it treats a Node pointer
as a tree vs. where it is treated as a list.
*/
/*
TreeList main methods:
-join() -- utility to connect two list nodes
-append() -- utility to append two lists
-treeToList() -- the core recursive function
-treeInsert() -- used to build the tree
*/
public class TreeList {
/*
helper function -- given two list nodes, join them
together so the second immediately follow the first.
Sets the .next of the first and the .previous of the second.
*/
public static void join(Node a, Node b) {
a.large = b;
b.small = a;
}
/*
helper function -- given two circular doubly linked
lists, append them and return the new list.
*/
public static Node append(Node a, Node b) {
// if either is null, return the other
if (a==null) return(b);
if (b==null) return(a);
// find the last node in each using the .previous pointer
Node aLast = a.small;
Node bLast = b.small;
// join the two together to make it connected and circular
join(aLast, b);
join(bLast, a);
return(a);
}
/*
--Recursion--
Given an ordered binary tree, recursively change it into
a circular doubly linked list which is returned.
*/
public static Node treeToList(Node root) {
// base case: empty tree -> empty list
if (root==null) return(null);
// Recursively do the subtrees (leap of faith!)
Node aList = treeToList(root.small);
Node bList = treeToList(root.large);
// Make the single root node into a list length-1
// in preparation for the appending
root.small = root;
root.large = root;
// At this point we have three lists, and it's
// just a matter of appending them together
// in the right order (aList, root, bList)
aList = append(aList, root);
aList = append(aList, bList);
return(aList);
}
/*
Given a non-empty tree, insert a new node in the proper
place. The tree must be non-empty because Java's lack
of reference variables makes that case and this
method messier than they should be.
*/
public static void treeInsert(Node root, int newData) {
if (newData<=root.data) {
if (root.small!=null) treeInsert(root.small, newData);
else root.small = new Node(newData);
}
else {
if (root.large!=null) treeInsert(root.large, newData);
else root.large = new Node(newData);
}
}
// Do an inorder traversal to print a tree
// Does not print the ending "\n"
public static void printTree(Node root) {
if (root==null) return;
printTree(root.small);
System.out.print(Integer.toString(root.data) + " ");
printTree(root.large);
}
// Do a traversal of the list and print it out
public static void printList(Node head) {
Node current = head;
while (current != null) {
System.out.print(Integer.toString(current.data) + " ");
current = current.large;
if (current == head) break;
}
System.out.println();
}
// Demonstrate tree->list with the list 1..5
public static void main(String[] args) {
// first build the tree shown in the problem document
// http://cslibrary.stanford.edu/109/
Node root = new Node(4);
treeInsert(root, 2);
treeInsert(root, 1);
treeInsert(root, 3);
treeInsert(root, 5);
System.out.println("tree:");
printTree(root); // 1 2 3 4 5
System.out.println();
System.out.println("list:");
Node head = treeToList(root);
printList(head); // 1 2 3 4 5 yay!
}
}
class Node {
int data;
Node small;
Node large;
public Node(int data) {
this.data = data;
small = null;
large = null;
}
}
Comments
Post a Comment