题目描述:
给你一棵二叉搜索树,请你返回一棵 平衡后 的二叉搜索树,新生成的树应该与原来的树有着相同的节点值。
如果一棵二叉搜索树中,每个节点的两棵子树高度差不超过 1 ,我们就称这棵二叉搜索树是 平衡的 。
如果有多种构造方法,请你返回任意一种。
思路分析:
1.先将二叉搜索树进行中序遍历存储在list中,是有序的,然后用list构建平衡二叉树;
2.每次需要找到list的中间值构造节点,然后依次递归构建左节点,右节点
class Solution {
List<Integer> list=new ArrayList<>();
public TreeNode balanceBST(TreeNode root) {
print(root);
return build(0,list.size()-1);
}
public TreeNode build(int start,int end){
if(start>end){
return null;
}
int mid=start+((end-start)>>1);
TreeNode node=new TreeNode(list.get(mid));
node.left=build(start,mid-1);
node.right=build(mid+1,end);
return node;
}
public void print(TreeNode root){
if(root!=null){
print(root.left);
list.add(root.val);
print(root.right);
}
}
}