题目
给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。
示例
输入:root = [3,9,20,null,null,15,7]
输出:true
输入:root = [1,2,2,3,3,null,null,4,4]
输出:false
示例 3:
输入:root = []
输出:true
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/balanced-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
方法1
递归。
1、isBalanced 函数定义:判断以root为根的树是否是平衡二叉树。
要分别判断左子树、右子树是否为平衡二叉树。
再判断以root为根的树是否是平衡二叉树(满足左右两个子树的高度差的绝对值不超过 1 )
2、height 函数定义:计算树的高度。+1 是加上了根本身。
Java实现1
class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null) return true;
return isBalanced(root.left) && isBalanced(root.right) && Math.abs(height(root.left) - height(root.right)) <= 1;
}
//计算树的高度
public int height(TreeNode root){
//base case
if (root == null) return 0;
int hl = height(root.left);
int hr = height(root.right);
return Math.max(hl, hr) + 1;
}
}
Java实现2
class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null) return true;
if (Math.abs(Depth(root.left) - Depth(root.right)) > 1) return false;
return isBalanced(root.left) && isBalanced(root.right);
}
public int Depth(TreeNode root) {
if (root == null) return 0;
return 1 + Math.max(Depth(root.left), Depth(root.right));
}
}