-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBSTToBalancedTree.java
More file actions
33 lines (24 loc) · 864 Bytes
/
BSTToBalancedTree.java
File metadata and controls
33 lines (24 loc) · 864 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
package BinarySearchTrees;
import java.util.Vector;
public class BSTToBalancedTree {
public static Node buildBalancedTree(Node root) {
Vector<Node> nodes = new Vector<>();
storeBSTNodes(root, nodes);
int n = nodes.size();
return buildTreeUtil(nodes, 0, n - 1);
}
public static void storeBSTNodes(Node root, Vector<Node> nodes) {
if (root == null) return;
storeBSTNodes(root.left, nodes);
nodes.add(root);
storeBSTNodes(root.right, nodes);
}
public static Node buildTreeUtil(Vector<Node> nodes, int start, int end) {
if (start > end) return null;
int mid = (start + end) / 2;
Node node = nodes.get(mid);
node.left = buildTreeUtil(nodes, start, mid - 1);
node.right = buildTreeUtil(nodes, mid + 1, end);
return node;
}
}