java练习(28)
ps:练习来自力扣
给定一个二叉树,判断它是否是平衡二叉树
// 定义二叉树节点类
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
class Solution {
public boolean isBalanced(TreeNode root) {
return getHeight(root) != -1;
}
private int getHeight(TreeNode node) {
// 如果当前节点为空,高度为 0
if (node == null) {
return 0;
}
// 递归计算左子树的高度
int leftHeight = getHeight(node.left);
// 如果左子树已经不平衡,直接返回 -1
if (leftHeight == -1) {
return -1;
}
// 递归计算右子树的高度
int rightHeight = getHeight(node.right);
// 如果右子树已经不平衡,直接返回 -1
if (rightHeight == -1) {
return -1;
}
// 判断当前节点的左右子树高度差是否超过 1
if (Math.abs(leftHeight - rightHeight) > 1) {
return -1;
}
// 如果当前节点平衡,返回其高度(左右子树最大高度加 1)
return Math.max(leftHeight, rightHeight) + 1;
}
}