-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTreeToBST.java
More file actions
35 lines (26 loc) · 921 Bytes
/
TreeToBST.java
File metadata and controls
35 lines (26 loc) · 921 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
package BinarySearchTrees;
import java.util.ArrayList;
import java.util.Collections;
public class TreeToBST {
static void storeInorder(Node node, ArrayList<Integer> inorder) {
if (node == null) return;
storeInorder(node.left, inorder);
inorder.add(node.val);
storeInorder(node.right, inorder);
}
public static Node helper(ArrayList<Integer> arr, int low, int high) {
if (low > high) return null;
int mid = low + (high - low) / 2;
Node root = new Node(arr.get(mid));
root.left = helper(arr, low, mid - 1);
root.right = helper(arr, mid + 1, high);
return root;
}
static Node binaryTreeToBST(Node root) {
if (root == null) return root;
ArrayList<Integer> arr = new ArrayList<>();
storeInorder(root, arr);
Collections.sort(arr);
return helper(arr, 0, arr.size() - 1);
}
}