110.判断一棵树是否是平衡二叉树

题目叙述:

给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。

思路 :

  • 要求以每一个结点为根节点的子树都是平衡的
    上面的问题等价于下面两个条件:
    1. 对于某一个根节点,其左子树平衡,右子树也平衡
    2. 左右子树的高度差的绝对值小于2

代码:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root == null) return true;
        if(root.left == null && root.right == null) return true;
        return isBalanced(root.left)&&isBalanced(root.right)&&Math.abs(height(root.left)-height(root.right))<=1;
    }
    //求一棵树的高度
    public int height(TreeNode root){
        if(root == null) return 0;
        return Math.max(height(root.left),height(root.right)) + 1;
    }
}
发布了126 篇原创文章 · 获赞 5 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/zhpf225/article/details/104476792
今日推荐