java判断一颗二叉树是否是平衡二叉树

判断一颗二叉树是否是平衡二叉树

题目描述

一棵高度平衡二叉树定义为: 一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。

示例

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

原题OJ链接

https://leetcode.cn/problems/balanced-binary-tree/

解答代码

/**
 * 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;
 *     }
 * }
 */
 import java.lang.Math;
class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root == null){
            return true;
        }
        int leftH = getHeight(root.left);
        int rightH = getHeight(root.right);
        if((Math.abs(leftH-rightH)<=1) && isBalanced(root.left) && isBalanced(root.right)){
            return true;
        }
        return false;


    }
    public int getHeight(TreeNode root){//求树的深度(高度)
        if(root == null){
            return 0;
        }
        if(root.right == null && root.left == null){
            return 1;
        }
//        int count1 = getHeight(root.left)+1;
//        int count2 = getHeight(root.right)+1;
//        return Math.max(count1,count2);
        return Math.max(getHeight(root.left)+1, getHeight(root.right)+1);
    }
}

这段代码有一个缺点在于实际做了很多重复的工作,实际是在进行双层递归,每个结点都求了其左右子树的高度,不满足之差绝对值小于等于1才会返回false,但是实际上这个工作可以直接放在求高度的时候完成,左右子树高度之差的绝对值大于1就直接返回-1,后面结点的高度根本不需要求了,因为这表明这个树一定是不平衡的了。
所以有如下代码

/**
 * 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;
 *     }
 * }
 */
 import java.lang.Math;
class Solution {
    public boolean isBalanced(TreeNode root) {
        return maxDepth(root)>=0;
    }
    public int maxDepth(TreeNode root){
        if(root == null){
            return 0;
        }
       int count1 = maxDepth(root.left);
       if(count1<0){
           return-1;
       } 
       int count2 = maxDepth(root.right);
       if(count2<0){
           return -1;
       }
       if(Math.abs(count1-count2)<=1){
           return Math.max(count1,count2)+1;
       }
       else{
           return -1;
       }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值