原题链接
题干
给定一个二叉树,判断它是否是平衡二叉树
示例 1:
输入: root = [3,9,20,null,null,15,7]
输出: true
思路
主要考察点:递归
- 终止条件:空子树返回0
- 传参:节点
- 单层递归逻辑:左右子树的高度之差小于1
解题
class Solution {
public boolean isBalanced(TreeNode root) {
return height(root) >= 0;
}
private int height(TreeNode root) {
if(root == null)
return 0;
int lh = height(root.left), rh = height(root.right);
if(lh >= 0 && rh >= 0 && Math.abs(lh - rh) <= 1) {
return Math.max(lh, rh) + 1;
} else {
return -1;
}
}
}