-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBST.java
More file actions
493 lines (405 loc) · 13.6 KB
/
BST.java
File metadata and controls
493 lines (405 loc) · 13.6 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
import java.util.*;
public class BST {
private Node root; // root of BST
public BST() {
root = null;
}
/**
* Inserting nodes depending on their key
* and the current structure of the BST
*/
public void insert(int k) {
Node x, y;
Node z= new Node(k);
y=null;
x=root;
while (x!=null) {
y=x;
if (x.key < z.key)
x=x.right;
else
x=x.left;
}
z.p=y;
if (y==null)
root=z;
else
if (y.key < z.key)
y.right=z;
else
y.left=z;
}
/**
* Inorder BST traversal
* Left, root, right
*/
public void inorder(Node node) {
if(node == null) return;
this.inorder(node.left);
System.out.print(node.key + " ");
this.inorder(node.right);
}
/**
* Preorder BST traversal
* Root, left, right
*/
public void preorder(Node node) {
if(node == null) return;
System.out.print(node.key + " ");
this.preorder(node.left);
this.preorder(node.right);
}
/**
* Postorder BST traversal
* Left, right, root
*/
public void postorder(Node node) {
if(node == null) return;
this.postorder(node.left);
this.postorder(node.right);
System.out.print(node.key + " ");
}
/**
* The height of the BST is the maximum
* length of a path from the root node
* to one of the leaves
*/
public int height(Node node) {
if(node == null) return 0;
else {
int heightR = height(node.right);
int heightL = height(node.left);
return (Math.max(heightL,heightR) + 1);
}
}
public int weightPrecalc(Node node) {
if(node == null) return 0;
else {
int weightR = weightPrecalc(node.right);
int weightL = weightPrecalc(node.left);
node.weight = weightL + weightR + 1;
return node.weight;
}
}
public void depthPrecalc(Node node) {
if(node == null) return;
else {
if(node.p != null) {
node.depth = node.p.depth + 1;
}
if(node.left != null) {
depthPrecalc(node.left);
}
if(node.right != null) {
depthPrecalc(node.right);
}
}
}
/**
* Searching for a node with the given key
* in the BST, return null if not found
*/
public Node search(int key, Node node) {
// base case, empty BST
if(node == null)
return null;
// if the keys match, the node is found
if(node.key == key)
return node;
// if node key is greater than given key we need to search in the left subtree of node, otherwise in the right one
if(node.key > key)
return search(key, node.left);
else
return search(key, node.right);
}
/**
* Used for returning the leftmost
* node from a subtree (with root node)
* that also has the minimum key value
* of that subtree
*/
private Node minVal(Node node) {
while(node.left != null) {
node = node.left;
}
return node;
}
/**
* Searching for the successor node of the given key
*/
public Node successor(Node root, Node node, int key) {
// empty tree, base case
if (root == null) {
return null;
}
// if the node with the given key was found and has a right child, then the succesor is that child's subtree minimum value
if (root.key == key && root.right != null) {
return this.minVal(root.right);
}
// same algorithm as the serching one, but also saving the node with greatest key value smaller then the given one
if (root.key > key)
{
node = root;
return successor(root.left, node, key);
}
if (root.key < key) {
return successor(root.right, node, key);
}
return node;
}
/**
* Check if the subtree with root node is perfectly balanced
* (difference of weight between left and right child is 1 at most)
* @param node
* @return
*/
public boolean isPerfectlyBalanced(Node node) {
if(node.right == null && node.left == null) return true;
else {
boolean balL = (node.left != null) ? isPerfectlyBalanced(node.left) : true;
boolean balR = (node.right != null) ? isPerfectlyBalanced(node.right) : true;
int balance = 0;
balance += (node.left != null) ? node.left.weight : 0;
balance -= (node.right != null) ? node.right.weight : 0;
boolean ok = (balance >= -1 && balance <= 1) ? true : false;
return (balL && balR && ok);
}
}
/**
* Given a fixed value k, find the node in the BST with
* closest value of key to k
* @param k
* @param node
* @param min_dif
* @return
*/
public Node searchClosest(int k, Node node, int min_dif) {
if(node == null) return null;
if(k == node.key) return node;
Node closest = null;
if(Math.abs(node.key - k) < min_dif) {
min_dif = Math.abs(node.key - k);
closest = node;
}
if(k < node.key) {
Node nL = searchClosest(k, node.left, min_dif);
if((nL != null) && Math.abs(nL.key - k) < min_dif) {
min_dif = Math.abs(nL.key - k);
closest = nL;
}
}
else {
Node nR = searchClosest(k, node.right, min_dif);
if((nR != null) && Math.abs(nR.key - k) < min_dif) {
min_dif = Math.abs(nR.key - k);
closest = nR;
}
}
return closest;
}
/**
* For a fixed sum, find two nodes that added match the sum
* @param sum
* @param node
* @param s
* @return
*/
public boolean checkExistTwoNodesWithSum(int sum, Node node, HashSet<Integer> s) {
if(node == null) return false;
int dif = sum - node.key;
boolean ok = false;
if(s.contains(dif)) {
System.out.println("Pair with given sum " + sum + " is (" + node.key + ", " + dif + ")");
ok = true;
}
s.add(node.key);
ok |= checkExistTwoNodesWithSum(sum, node.left, s);
ok |= checkExistTwoNodesWithSum(sum, node.right, s);
return ok;
}
/**
* From a src node k1 and a dest node k2
* fint the shortest path, trough the
* lowest common ancestor
* @param k1
* @param k2
* @param root
*/
public void printPathFromTo(int k1, int k2, Node root) {
Node n1 = search(k1, root);
Node n2 = search(k2, root);
if(n1 == null || n2 == null) return;
System.out.println("The path from " + n1 + " to " + n2 + " is: ");
System.out.println(n1);
while(n1.depth != n2.depth) {
if(n1.depth > n2.depth) {
n1 = n1.p;
System.out.println(n1);
}
else {
n2 = n2.p;
}
}
while(n1 != n2) {
n1 = n1.p;
n2 = n2.p;
System.out.println(n1);
}
while(n1.key != k2) {
if(n1.key < k2) {
n1 = n1.right;
}
else {
n1 = n1.left;
}
System.out.println(n1);
}
}
/**
* Given a fixed sum print the paths with added elements
* matching the sum. Beggining with the root of the tree
* and ending with one of the leaves
* @param sum
* @param node
* @param path
* @param crt
*/
public void printPathsWithSum(int sum, Node node, Vector<Integer> path, int crt) {
if(node == null) return;
path.add(node.key);
if((crt + node.key) == sum) {
for(int j = 0 ; j < path.size() ; ++j) {
System.out.print(path.get(j) + " ");
}
System.out.println();
}
printPathsWithSum(sum, node.left, path, crt + node.key);
printPathsWithSum(sum, node.right, path, crt + node.key);
path.remove(path.size() - 1);
}
/**
* Print the keys of the nodes in depth order
* The nodes with the same depth are printed
* from smallest to biggest
* @param root
*/
public void printLevels(Node root) {
Queue<Node> q = new LinkedList<Node>();
q.add(root);
int depth = -1;
while(q.size() > 0) {
Node head = q.poll();
if(head.left != null) q.add(head.left);
if(head.right != null) q.add(head.right);
if(depth != head.depth) {
System.out.println("\nLevel " + head.depth + ":");
depth = head.depth;
}
System.out.print(head.key + " ");
}
System.out.println();
}
/**
* Given a sorted array (inorder traversal),
* construct the BST coresponding with that keys
*/
public Node createBalancedBSTfromSortedArray(int arr[], int start, int end) {
if(start > end) return null;
int mid = (start + end) / 2;
Node node = new Node(arr[mid]);
node.left = createBalancedBSTfromSortedArray(arr, start, mid - 1);
node.right = createBalancedBSTfromSortedArray(arr, mid + 1, end);
return node;
}
/**
* For a postorder traversal array check if
* it can be transformed in a BST
* @param arr
* @param start
* @param end
* @return
*/
public boolean isPostorderArray(int arr[], int start, int end) {
if(start >= end) return true;
int i, tmp;
for(i = end - 1 ; i >= start && arr[end] < arr[i] ; --i);
tmp = i;
for(; i >= start ; --i) {
if(arr[end] < arr[i])
return false;
}
if(tmp == start) return isPostorderArray(arr, start, end - 1);
else return (isPostorderArray(arr, start, tmp) && isPostorderArray(arr, tmp + 1, end - 1));
}
/**
* Using a BST postorder traversal
* create the coresponging BST and return it's root
* @param arr
* @param start
* @param end
* @return
*/
public Node createBSTfromPostOrderArray(int arr[], int start, int end) {
if(start > end) return null;
Node root = new Node(arr[end]);
int i;
for(i = end ; i >= start ; --i) {
if(arr[i] < root.key)
break;
}
root.left = createBSTfromPostOrderArray(arr, start, i);
root.right = createBSTfromPostOrderArray(arr, i + 1, end - 1);
return root;
}
public static void main(String[] args) {
BST st1 = new BST();
HashSet<Integer> s = new HashSet<Integer>();
Vector<Integer> path = new Vector<Integer>();
int arr[] = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9};
int arrTrue[] = new int[]{1, 5, 2, 15, 8};
int arrFalse[] = new int[]{1, 15, 2, 5, 8};
st1.insert(5);
st1.insert(2);
st1.insert(10);
st1.insert(8);
st1.insert(15);
/**
* 5
* / \
* 2 10
* / \
* 8 15
*/
st1.root.depth = 0;
st1.depthPrecalc(st1.root);
st1.weightPrecalc(st1.root);
System.out.println("\n>>>>>>>>>>>\nInorder:");
st1.inorder(st1.root); // 2 5 8 10 15
System.out.println("\n>>>>>>>>>>>\nPreorder:");
st1.preorder(st1.root); // 5 2 10 8 15
System.out.println("\n>>>>>>>>>>>\nPostorder:");
st1.postorder(st1.root); // 2 8 15 10 5
System.out.println("\n>>>>>>>>>>>");
System.out.println("Height: " + st1.height(st1.root)); // Height: 3
System.out.println("\n>>>>>>>>>>>");
System.out.println(st1.search(Integer.valueOf(2),st1.root)); // Key: 2
System.out.println(st1.search(Integer.valueOf(4),st1.root)); // null
System.out.println("\n>>>>>>>>>>>");
System.out.println(st1.successor(st1.root,null,Integer.valueOf(8))); // Key: 10
System.out.println(st1.successor(st1.root,null,Integer.valueOf(15))); // null
System.out.println("\n>>>>>>>>>>>");
System.out.println(st1.isPerfectlyBalanced(st1.root));
System.out.println(st1.searchClosest(16, st1.root, Integer.MAX_VALUE));
System.out.println(st1.checkExistTwoNodesWithSum(12, st1.root, s));
st1.printPathFromTo(Integer.valueOf(2), Integer.valueOf(10), st1.root);
st1.printPathsWithSum(30, st1.root, path, Integer.valueOf(0));
st1.printLevels(st1.root);
Node root2 = st1.createBalancedBSTfromSortedArray(arr, 0, arr.length - 1);
st1.preorder(root2); // 5 2 1 3 4 7 6 8 9
System.out.println();
System.out.println(st1.isPostorderArray(arrTrue, 0, arrTrue.length - 1));
System.out.println(st1.isPostorderArray(arrFalse, 0 , arrFalse.length - 1));
Node root3 = st1.createBSTfromPostOrderArray(arrTrue, 0, arrTrue.length - 1);
st1.inorder(root3);
}
}