The tree [w] B019_ becomes balanced binary search tree (recursive)

One, Title Description

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.

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.

Second, the problem solution

Method a: dfs + preorder

List<Integer> nums;
public TreeNode balanceBST(TreeNode root) {
  nums = new ArrayList<>();
  inOrder(root);
  return dfs(0, nums.size());
}
//构造
TreeNode dfs(int l, int r) {
  TreeNode root = null;
  if (l == r) {
    return root;
  }
  int mid = (l + r) >>> 1;
  root = new TreeNode(nums.get(mid));
  root.left =  dfs(l, mid);
  root.right = dfs(mid + 1, r);
  return root;
}
//得到有序数组
void inOrder(TreeNode root) {
  if (root == null)
    return;
  inOrder(root.left);
  nums.add(root.val);
  inOrder(root.right);
}

Complexity Analysis

  • time complexity: O ( n ) O (n) ,
  • Space complexity: O ( n ) O (n) ,
Published 495 original articles · won praise 105 · views 30000 +

Guess you like

Origin blog.csdn.net/qq_43539599/article/details/104880398