package Balance;
/**
* @author 真他喵的学不动咯
* @create 2022-08-16--19:52
*/
public class Bala { //平衡二叉树
//https://leetcode.com/problems/balanced-binary-tree/
public static class TreeNode{
public int val;
public TreeNode left;
public TreeNode right;
TreeNode(int val){
this.val=val;
}
}
//假设以某节点为头,返回以下两个信息,1.是否平衡2.树的高度
public static class Info{
public boolean isBalanced;
public int height;
public Info(boolean i,int h){
isBalanced =i;
height=h;
}
}
//
public static Info process(TreeNode x){ //x计算的结果返回【Info】两个信息:1.是否平衡2.树高度
//边界条件
if (x==null){ //x是树,x是空树
return new Info(true,0); //是true平衡树,高度为0
}
//普通情况
//当不是空树
//用递归
Info leftInfo=process(x.left);
Info rightInfo=process(x.right);
int height =Math.max(leftInfo.height,rightInfo.height)+1; //左树或者右树的最大高度+1【这个1是头结点】,就是这树的高度
boolean isBalanced=leftInfo.isBalanced&&rightInfo.isBalanced&&Math.abs(leftInfo.height-rightInfo.height)<2;//比较两个信息
return new Info(isBalanced,height);
}
}
10-09
889
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)