leetCode 110.Balanced Binary Tree (平衡二叉树) 解题思路和方法

本文介绍了一种通过深度优先搜索(DFS)判断二叉树是否为平衡二叉树的方法。平衡二叉树定义为任意节点的两个子树的深度之差不大于1。通过递归计算各子树的高度并比较来实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

思路:判断是否是平衡二叉树,dfs即可,递归判断每个子树是否平衡二叉树,如果有子树不满足,则整体也不满足。

具体代码如下:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    /**
     * 判断是否平衡二叉树
     * 看左右子树高度差是否超过1
     * 不超过1则分别判断左右子树是否平衡二叉树
     */ 
    public boolean isBalanced(TreeNode root) {
        if(root == null)
            return true;
        if(dep(0,root) > - 10)
        	return true;
        return false;
    }
    //计算树的高度
    private int dep(int dep,TreeNode root){
        if(root == null){
            return dep-1;
        }
        int dep1 = dep(dep+1,root.left);
        int dep2 = dep(dep+1,root.right);
        //如果高度差超过1,返回-10
        //则以后的dep返回值均为-10
        if(Math.abs(dep1 - dep2) > 1){
        	return -10;
        }
        return dep1 > dep2 ? dep1 : dep2;
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值