题目如下:
Determine if a binary tree is height-balanced.
Eg.:
Input: root = [1,2,2,3,3,null,null,4,4] Output: false
********
平衡二叉树的定义很重要:空树,或左子树、右子树深度相差不超过1。
递归思路:
- isBalanced方法的返回类型是boolean,但针对每一节点,不仅需要记录左子树、右子树是否平衡,还有该节点在数内的深度。深度信息的类型是int,与boolean类型不兼容。
- 运用sentinel value的概念,使“-1”代表不平衡状态,统一返回类型。
- 求左子树、右子树状态,分别递归检查该子树的子树是否已存在不平衡状态。若存在,传递不平衡状态。若不存在,深度 +1。
该递归思路符合递归三要素:
- base case:空树深度为0。
- function:若平衡,返回深度。若不平衡,返回-1。
- equivalence relations:只要出现不平衡子树,不平衡状态会一直被传递。平衡子树节点深度递增。
解法如下:
class Solution {
public boolean isBalanced(TreeNode root) {
return height(root) != -1;
}
public int height(TreeNode root) {
// base case
if (root == null) {
return 0;
}
// get height of left subtree
int leftHeight = height(root.left);
// if left subtree unbalanced, tree unbalanced
if (leftHeight == -1) {
return -1;
}
// get height of right subtree
int rightHeight = height(root.right);
// if right subtree unbalanced, tree unbalanced
if (rightHeight == -1) {
return -1;
}
// definition of unbalance
if (Math.abs(leftHeight - rightHeight) > 1) {
return -1;
}
return Math.max(leftHeight, rightHeight) + 1;
}
}