import java.util.LinkedList;
import java.util.Queue;
/**
* 平衡二叉树
*
* 输入一棵二叉树,判断该二叉树是否是平衡二叉树。
*
* 在这里,我们只需要考虑其平衡性,不需要考虑其是不是排序二叉树
*/
public class JZ039IsBalanced {
public boolean IsBalanced_Solution(TreeNode root) {
if (root == null) {
return true;
}
int leftDepth = treeDepth(root.left);
int rightDepth = treeDepth(root.right);
int diff = Math.abs(leftDepth - rightDepth);
if (diff > 1) {
return false;
}
return IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
}
private int treeDepth(TreeNode root) {
if (root == null) {
return 0;
}
int leftDepth = treeDepth(root.left);
int rightDepth = treeDepth(root.right);
return Math.max(leftDepth, rightDepth) + 1;
}
private int treeDepth2(TreeNode root) {
if (root == null) {
return 0;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
int nextCount = queue.size();
int count = 0;
int depth = 0;
while (queue.size() > 0) {
TreeNode topNode = queue.poll();
count++;
if (topNode.left != null) {
queue.add(topNode.left);
}
if (topNode.right != null) {
queue.add(topNode.right);
}
if (count == nextCount) {
nextCount = queue.size();
count = 0;
depth++;
}
}
return depth;
}
/*
平衡二叉树
总结:
获取左右子树的深度,根据深度来判断
每个节点的都需要对其左右子树判断
什么是平衡二叉树,什么是排序二叉树
*/
}