# 经典二叉树知识点：平衡二叉树

leetcode110：leetcode-cn.com/problems/ba…

## 题意

Given a binary tree, determine if it is height-balanced.

• determine v.确定，决定，判定。

For this problem, a height-balanced binary tree is defined as:

a binary tree in which the left and right subtrees of every node differ in height by no more than 1.

## 编码

``````class Solution {
public boolean isBalanced(TreeNode root) {
if(root == null) {
return true;
}
int leftDepth = getDepth(root.left, 0);
if(leftDepth < 0) {
return false;
}
int rightDepth = getDepth(root.right, 0);
if(rightDepth < 0) {
return false;
}

return abs(leftDepth - rightDepth) > 1 ? false : true;
}

private int getDepth(TreeNode root, int currentDepth) {
if(root == null) {
return currentDepth;
}

int leftDepth = getDepth(root.left, currentDepth + 1);
if(leftDepth < 0) {
return -1;
}
int rightDepth = getDepth(root.right, currentDepth + 1);
if(rightDepth < 0) {
return -1;
}
if(abs(leftDepth - rightDepth) > 1) {
return -1;
}
return leftDepth > rightDepth ? leftDepth : rightDepth;

}

private int abs(int a) {
return a > 0 ? a : -a;
}

}