-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_1382_BalanceBST.java
More file actions
66 lines (50 loc) · 1.58 KB
/
_1382_BalanceBST.java
File metadata and controls
66 lines (50 loc) · 1.58 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
import java.util.ArrayList;
import java.util.List;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
List<Integer> inorder = new ArrayList<>();
// Step 1: balance BST
public TreeNode balanceBST(TreeNode root) {
inorder.clear();
fillInorder(root); // list fill
return buildBalancedBST(0, inorder.size() - 1);
}
// Step 2: build balanced tree
private TreeNode buildBalancedBST(int left, int right) {
if (left > right) return null;
int mid = left + (right - left) / 2;
TreeNode root = new TreeNode(inorder.get(mid));
root.left = buildBalancedBST(left, mid - 1);
root.right = buildBalancedBST(mid + 1, right);
return root;
}
// inorder for LIST
void fillInorder(TreeNode root) {
if (root == null) return;
fillInorder(root.left);
inorder.add(root.val);
fillInorder(root.right);
}
// inorder for PRINT
void printInorder(TreeNode root) {
if (root == null) return;
printInorder(root.left);
System.out.print(root.val + " ");
printInorder(root.right);
}
}
public class _1382_BalanceBST {
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
root.right = new TreeNode(2);
root.right.right = new TreeNode(3);
root.right.right.right = new TreeNode(4);
TreeNode balancedRoot = root.balanceBST(root);
balancedRoot.printInorder(balancedRoot); // ✅ no NPE
}
}