Java实现判断二叉树是否为平衡二叉树
两种方法:自顶向下、自顶向上
实现方法
1、自顶向下
height方法为判断该节点高度
当出现左右子树的高度差大于一时返回false
每个节点判断一遍高度
//自顶向下
//时间复杂度:O(n²)
//空间复杂度:O(n)
private static boolean isBalanced(TreeNode root) {
if (root == null)
return true;
if (Math.abs(height(root.left) - height(root.right)) <= 1)
return isBalanced(root.left) && isBalanced(root.right);
return false;
}
private static int height(TreeNode root) {
if (root == null)
return 0;
else
return Math.max(height(root.left), height(root.right)) + 1;
}
2、自顶向上
从最下面开始,结合高度和判断平衡
若高度差>1则返回-1,返回false
时间复杂度较上一种小得多
//自顶向上
//时间复杂度:O(n)
//空间复杂度:O(n)
public boolean isBalanced(TreeNode root) {
return height(root) >= 0;
}
private int height(TreeNode root) {
if (root == null)
return 0;
int left = height(root.left);
int right = height(root.right);
if (left == -1 || right == -1 || Math.abs(left-right) > 1)
return -1;
else
return Math.max(left, right) + 1;
}