leetcode刷题之 树(2)-递归:平衡树

博客围绕LeetCode的平衡二叉树问题展开,给出高度平衡二叉树的定义,即每个结点的两个子树深度差不超1。介绍求解思路,需一个求各点深度的函数,对每个节点的子树比较深度差,时间复杂度为O(NlgN),还提及与前一题的关联。

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

[LeetCode] 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 everynode never differ by more than 1.

Example 1:

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

    3
   / \
  9  20
    /  \
   15   7

Return true.

Example 2:

Given the following tree [1,2,2,3,3,null,null,4,4]:

       1
      / \
     2   2
    / \
   3   3
  / \
 4   4

Return false.

求二叉树是否平衡,根据题目中的定义,高度平衡二叉树是每一个结点的两个子树的深度差不能超过1,那么我们肯定需要一个求各个点深度的函数,然后对每个节点的两个子树来比较深度差,时间复杂度为O(NlgN),代码如下:

其实就是前一道计算各个节点高度的题目 我们增加一个比较环节

class Solution {
    boolean result = true;
    public boolean isBalanced(TreeNode root) {
        height(root);
        return result;
           
    }
    
    private int height(TreeNode root){
        if(root == null)
            return 0;
        if(root.left == null && root.right == null)
            return 1;
        int left = height(root.left);
        int right = height(root.right);
        if(Math.abs(left - right) > 1)
            result = false;
        return Math.max(left, right) + 1;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值