110. Balanced Binary Tree

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 depth of the two subtrees of every node never differ by more than 1.

Given the following tree [3,9,20,null,null,15,7]:
Return true.

思路:这道题需要判断给一个root,是不是平衡二叉树
判断平衡二叉树的标准是左右子树高度之差不大于1,左右子树都分别平衡,所以不仅要判断,还要有高度进行判断,自己新建一个新的数据类型resultType:

class resultType{
    public boolean isBal;
    public int maxdepth;
    public resultType(boolean isBal,int maxdepth){
        this.isBal=isBal;
        this.maxdepth=maxdepth;
    }
}

然后进行遍历,出口是root遍历到叶子节点,有以下几种情况:

  1. 左右都不平衡
  2. root这里就不平衡:左右子树高度之差大于1
  3. 平衡
    如果平衡的话,返回true,高度是左右子树最大高度+1
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
//返回需要返回两个值,一个是否为平衡二叉树,一个是计算二叉树高度
class resultType{
    public boolean isBal;
    public int maxdepth;
    public resultType(boolean isBal,int maxdepth){
        this.isBal=isBal;
        this.maxdepth=maxdepth;
    }
}
public class Solution {
    
    //平衡二叉树:左右子树之差不大于一 
    public boolean isBalanced(TreeNode root) {
        return helper(root).isBal;
    }
    //1.定义:以root为根的二叉树是否平衡,以及它的高度为多少
    private resultType helper(TreeNode root){
        
    //3.出口:叶子节点
        if(root==null){
            return new resultType(true,0);
        }
        
    //2.split
        resultType left=helper(root.left);
        resultType right=helper(root.right);
        
    //if subtree is not banlanced
        if(!left.isBal||!right.isBal){
            return  new resultType(false,1);
        }
    
    //if the root are not balanced
        if(Math.abs(left.maxdepth-right.maxdepth)>1){
            return new resultType(false,1);
        }
        
    //if balance
        int dep=Math.max(left.maxdepth,right.maxdepth)+1;
        return new resultType(true, dep);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值