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.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/balanced-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
/**
* @Auther: match
* @Date: 2021/2/20 11:06
* @Description:
* 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.
*
* 一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。
* https://leetcode-cn.com/problems/balanced-binary-tree/
*/
public class IsBalanced {
//方法一:自顶向下遍历,类似前序遍历 https://leetcode-cn.com/problems/balanced-binary-tree/solution/ping-heng-er-cha-shu-by-leetcode-solution/
public boolean isBalanced(TreeNode root) {
if(root == null){
return true;
}else{
return Math.abs(height(root.left) - height(root.right)) <=1 && isBalanced(root.left) && isBalanced(root.right);
}
}
//求二叉树树高度的函数,记得模板
public int height(TreeNode root){
if(root==null){
return 0;
}else{
return Math.max(height(root.left),height(root.right))+1;
}
}
//方法二:自底向上:类似后序遍历
public boolean isBalanced2(TreeNode root){
return h2(root) >=0;
}
public int h2(TreeNode root){
if(root == null){
return 0;
}
int leftHeight = h2(root.left);
int rightHeight = h2(root.right);
if(leftHeight == -1 || rightHeight == -1 || Math.abs(leftHeight - rightHeight) >1){//如果不满足,则返回-1,
return -1;
}else{
return Math.max(leftHeight,rightHeight) +1;
}
}
}