Skip to content

Commit 17773a4

Browse files
committed
bst to double linked list
1 parent 8a529be commit 17773a4

1 file changed

Lines changed: 74 additions & 0 deletions

File tree

PuzzleCoding/src/BSTtoDLL.java

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
import java.util.ArrayList;
2+
import java.util.Stack;
3+
4+
/**
5+
* Convert a BST to a sorted circular doubly-linked list in-place.
6+
* Think of the left and right pointers as synonymous to the previous
7+
* and next pointers in a doubly-linked list.
8+
* <p/>
9+
* This is a modified in-order traversal adapted to this problem.
10+
* prev (init to NULL) is used to keep track of previously traversed node.
11+
* head pointer is updated with the list's head as recursion ends.
12+
* <p/>
13+
* do it in place. time complexity: O(n)
14+
*/
15+
public class BSTtoDLL {
16+
public static void main(String[] args) {
17+
Node root = new Node(10);
18+
Node node5 = new Node(5);
19+
Node node15 = new Node(15);
20+
Node node6 = new Node(6);
21+
Node node20 = new Node(20);
22+
Node node3 = new Node(3);
23+
Node node12 = new Node(12);
24+
25+
root.insert(node5);
26+
root.insert(node6);
27+
root.insert(node15);
28+
root.insert(node20);
29+
root.insert(node3);
30+
root.insert(node12);
31+
32+
ArrayList<Node> dll = bstToDLL(root);
33+
printDll(dll);
34+
35+
}
36+
37+
38+
public static void printDll(ArrayList<Node> dll) {
39+
if (dll.size() != 0) {
40+
for(Node n:dll){
41+
System.out.print(n.value + " ");
42+
}
43+
}
44+
}
45+
46+
// not in place
47+
public static ArrayList<Node> bstToDLL(Node node) {
48+
if (node == null)
49+
return null;
50+
51+
Stack<Node> stack = new Stack<Node>();
52+
ArrayList<Node> dll = new ArrayList<Node>();
53+
Node current = node;
54+
boolean done = false;
55+
while (!done){
56+
if(current != null){
57+
stack.push(current);
58+
current = current.left;
59+
}else {
60+
if(stack.isEmpty()){
61+
done = true;
62+
}
63+
else {
64+
current = stack.pop();
65+
dll.add(current);
66+
current = current.right;
67+
}
68+
}
69+
}
70+
return dll;
71+
}
72+
73+
74+
}

0 commit comments

Comments
 (0)