MrainW's Home

All things come to those who wait!

0%

LeetCode 1382. Balance a Binary Search Tree

Question

Given the root of a binary search tree, return a balanced binary search tree with the same node values. If there is more than one answer, return any of them.

A binary search tree is balanced if the depth of the two subtrees of every node never differs by more than 1.

https://leetcode.com/problems/balance-a-binary-search-tree/

Solution

  • Solution1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public TreeNode balanceBST(TreeNode root) {
List<Integer> res = new ArrayList<>();
dfs(root, res);
return bulid(0, res.size() - 1, res);
}
private void dfs(TreeNode root, List<Integer> res){
if (root == null) return;
dfs(root.left, res);
res.add(root.val);
dfs(root.right, res);
}
private TreeNode bulid(int left, int right, List<Integer> res){
if (left > right) return null;
int mid = left + (right - left)/ 2;
TreeNode root = new TreeNode(res.get(mid));
root.left = bulid(left, mid - 1, res);
root.right = bulid(mid + 1, right, res);
return root;
}
}

Complexity:

Time complexity: O(n)

Space complexity: O(n)

Welcome to my other publishing channels