-
Notifications
You must be signed in to change notification settings - Fork 0
/
BST to Circular DLL
55 lines (45 loc) · 1.75 KB
/
BST to Circular DLL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
public Node concatenate(Node leftList,Node rightList)
{
// If either of the list is empty, then
// return the other list
if (leftList == null)
return rightList;
if (rightList == null)
return leftList;
// Store the last Node of left List
Node leftLast = leftList.left;
// Store the last Node of right List
Node rightLast = rightList.left;
// Connect the last node of Left List
// with the first Node of the right List
leftLast.right = rightList;
rightList.left = leftLast;
// left of first node refers to
// the last node in the list
leftList.left = rightLast;
// Right of last node refers to the first
// node of the List
rightLast.right = leftList;
// Return the Head of the List
return leftList;
}
// Method converts a tree to a circular
// Link List and then returns the head
// of the Link List
public Node bTreeToCList(Node root)
{
if (root == null)
return null;
// Recursively convert left and right subtrees
Node left = bTreeToCList(root.left);
Node right = bTreeToCList(root.right);
// Make a circular linked list of single node
// (or root). To do so, make the right and
// left pointers of this node point to itself
root.left = root.right = root;
// Step 1 (concatenate the left list with the list
// with single node, i.e., current node)
// Step 2 (concatenate the returned list with the
// right List)
return concatenate(concatenate(left, root), right);
}