Saturday, January 30, 2016

Convert BST to circular doubly linked list

Problem: Convert a BST to a sorted circular doubly-linked list in-place.
Solution:
/*
* Given an BST tree, recursively change it into a circular doubly linked list.
*/
public static Node treeToList(Node root) {
// base case: empty tree -> empty list
if (root==null) return(null);
// Recursively do the subtrees
Node aList = treeToList(root.left);
Node bList = treeToList(root.right);
// Make the single root node into a list length-1
root.left= root;
root.right = 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 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.left;
Node bLast = b.left;
// join the two together to make it connected and circular
join(aLast, b);
join(bLast, a);
return(a);
}
/*
* Given two list nodes, join them together so that second immediately follow the first.
*/
public static void join(Node a, Node b) {
a.right = b;
b.left = a;
}

3 comments: