import java.util.*;
public class Solution {
// 判断平衡二叉树,
// 思路:平衡二叉树,要保证所有左右子树的高度差不能大于1
// 1. 计算树的高度
// 2. 计算左右子树的高度差
// 3. 使用bfs遍历所有子树
public boolean IsBalanced_Solution (TreeNode pRoot) {
// write code here
// 如果是空树,也属于平衡二叉树
if(pRoot == null) return true;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(pRoot);
while(!queue.isEmpty()){
TreeNode node = queue.poll();
if(!judge(node)){
return false;
}
if(node.left != null) queue.add(node.left);
if(node.right != null) queue.add(node.right);
}
return true;
}
public int depthOfTree(TreeNode root){
if(root == null) return 0;
return Math.max(depthOfTree(root.left),depthOfTree(root.right)) + 1;
}
public boolean judge(TreeNode root){
int depthOfLeft = depthOfTree(root.left);
int depthOfRight = depthOfTree(root.right);
if(Math.abs(depthOfLeft - depthOfRight) > 1){
return false;
}
return true;
}
}