1382. Balance a Binary Search Tree
Given a binary search tree, return a balanced binary search tree with the same node values.
A binary search tree is balanced if and only if the depth of the two subtrees of every node never differ by more than 1.
If there is more than one answer, return any of them.
Example 1:
Input: root = [1,null,2,null,3,null,4,null,null] Output: [2,1,3,null,null,null,4] Explanation: This is not the only correct answer, [3,1,4,null,2,null,null] is also correct.
1 class Solution { 2 List<TreeNode> sortedArr = new ArrayList<>(); 3 public TreeNode balanceBST(TreeNode root) { 4 inorderTraverse(root); 5 return sortedArrayToBST(0, sortedArr.size() - 1); 6 } 7 void inorderTraverse(TreeNode root) { 8 if (root == null) return; 9 inorderTraverse(root.left); 10 sortedArr.add(root); 11 inorderTraverse(root.right); 12 } 13 TreeNode sortedArrayToBST(int start, int end) { 14 if (start > end) return null; 15 int mid = (start + end) / 2; 16 TreeNode root = sortedArr.get(mid); 17 root.left = sortedArrayToBST(start, mid - 1); 18 root.right = sortedArrayToBST(mid + 1, end); 19 return root; 20 } 21 }