- 题目描述:
给定一个二叉树,判断它是否是高度平衡的二叉树。一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。1 - 代码:
class Solution {
public boolean isBalanced(TreeNode root) {
//判断二叉树是否为平衡数
if(root == null) return true;
return helper(root)&&isBalanced(root.left)&&isBalanced(root.right);
}
public boolean helper(TreeNode root){
//判断以root为根节点的二叉树是否为平衡树
if(root == null) return true;
int l = height(root.left);
int r = height(root.right);
return Math.abs(l-r)<=1;
}
public int height(TreeNode root){
//计算二叉树的高度
if(root == null) return 0;
if(root.left == null && root.right == null) return 1;
int l = height(root.left);
int r = height(root.right);
return Math.max(l,r)+1;
}
}
https://leetcode-cn.com/problems/balanced-binary-tree/ ↩︎