Given a binary tree, determine if it is height-balanced. 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.
Example1:
Input: root = [3,9,20,null,null,15,7]
Output: true
Example2:
Input: root = [1,2,2,3,3,null,null,4,4]
Output: false
Example3:
Input: root = []
Output: true
Constraints:
- The number of nodes in the tree is in the range [0, 5000].
- -104 <= Node.val <= 104
所谓的平衡二叉树,就是每一棵树左右子树的高度差小于1。这道题可以用递归,但是判断当前树是不是平衡,就需要高度的信息,所以递归的时候要返回这个信息。除此之外,每棵子树是不是平衡的信息也要返回,因为有的时候在底层不平衡,但是上层的左右子树差是1。
注意:
- 有的时候递归需要一些其他辅助的信息,这时候递归返回的是一个class,里面都包含了需要的信息。
/**
* Definition for a binary tree node.
* public 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;
* }
* }
*/
public class Info {
boolean isBalanced;
int hight;
Info(boolean isBalanced, int hight){
this.isBalanced = isBalanced;
this.hight = hight;
}
}
class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null) {
return true;
}
Info rst = helper(root);
return rst.isBalanced;
}
private Info helper(TreeNode root) {
if (root == null) {
return new Info(true, 0);
}
Info l = helper(root.left);
Info r = helper(root.right);
return new Info(l.isBalanced && r.isBalanced && (Math.abs(l.hight - r.hight) < 2),
Math.max(l.hight, r.hight) + 1);
}
}