题目
给你一棵二叉搜索树,请你返回一棵 平衡后 的二叉搜索树,新生成的树应该与原来的树有着相同的节点值。如果有多种构造方法,请你返回任意一种。
如果一棵二叉搜索树中,每个节点的两棵子树高度差不超过 1 ,我们就称这棵二叉搜索树是 平衡的 。
思路
根据中序遍历,将二叉树结点依次存入一个ArrayList数组中,将有序树转成有序数组,然后将 有序数组转成平衡二叉树
代码
class Solution {
List<Integer> res = new ArrayList<>();
public TreeNode balanceBST(TreeNode root) {
transel(root);
return getbalance(res,0,res.size()-1);
}
public void transel(TreeNode cur){
if(cur==null){ //递归终止条件
return;
}
transel(cur.left);
res.add(cur.val);
transel(cur.right);
}
public TreeNode getbalance( List<Integer> res,int low,int high){
if (low> high) return null;
int mid=low+(high-low)/2;
TreeNode root=new TreeNode(res.get(mid));
root.left=getbalance(res,low,mid-1);
root.right=getbalance(res,mid+1,high);
return root;
}
}