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);
* 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);
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;
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);
// 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);
* 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;
Node aLast = a.left;
Node bLast = b.left;
// join the two together to make it connected and circular
join(aLast, b);
join(bLast, a);
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;
}
* 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;
}
aLast could be null, couldn't it be?
ReplyDeleteaLast could be null, couldn't it be?
ReplyDeleteYes aLast could be null. Need to add null checks.
Delete