-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinary Tree to BST.java
More file actions
46 lines (43 loc) · 1.07 KB
/
Copy pathBinary Tree to BST.java
File metadata and controls
46 lines (43 loc) · 1.07 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
import java.util.*;
class Node
{
int data;
Node left, right;
Node(int item){
data = item;
left = right = null;
}
}
class Solution
{
private static Node constructBST(ArrayList<Integer> in, int l, int r) {
if (l > r) {
return null;
}
int mid = (l + r) / 2;
Node root = new Node(in.get(mid));
root.left = constructBST(in, l, mid - 1);
root.right = constructBST(in, mid + 1, r);
return root;
}
private static void inorder(Node root, ArrayList<Integer> in) {
if (root == null) {
return;
}
inorder(root.left, in);
in.add(root.data);
inorder(root.right, in);
}
// The given root is the root of the Binary Tree
// Return the root of the generated BST
Node binaryTreeToBST(Node root)
{
if (root == null) {
return null;
}
ArrayList<Integer> in = new ArrayList<>();
inorder(root, in);
Collections.sort(in);
return constructBST(in, 0, in.size() - 1);
}
}