-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBstToMeanHeap.java
More file actions
45 lines (34 loc) · 1007 Bytes
/
BstToMeanHeap.java
File metadata and controls
45 lines (34 loc) · 1007 Bytes
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
package priorityQueue;
import java.util.ArrayList;
/**
* For min heap, we do preorder and for max heap we do postorder.
*/
public class BstToMeanHeap {
static int index;
private static void bstToArray(Node root, ArrayList<Integer> arr) {
if (root == null) return;
bstToArray(root.left, arr);
arr.add(root.data);
bstToArray(root.right, arr);
}
private static void arrToMinHeap(Node root, ArrayList<Integer> arr) {
if (root == null) return;
root.data = arr.get(index++);
arrToMinHeap(root.left, arr);
arrToMinHeap(root.right, arr);
}
public static void convertToMinHeap(Node root) {
index = 0;
ArrayList<Integer> arr = new ArrayList<>();
bstToArray(root, arr);
arrToMinHeap(root, arr);
}
static class Node {
int data;
Node left, right;
Node(int data) {
this.data = data;
this.left = this.right = null;
}
}
}