【leetcode】Balanced Binary Tree(middle)

本文介绍了一种高效判断二叉树是否平衡的方法,并给出了简洁的实现代码。通过递归计算每个节点的左右子树深度,确保任意两子树深度差不超过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.

 

思路:

我居然在这道题上卡了一个小时。关键是对于平衡的定义,我开始理解错了,我以为是要所有叶节点的高度差不大于1.

但题目中的定义是如下这样的:

Below is a representation of the tree input: {1,2,2,3,3,3,3,4,4,4,4,4,4,#,#,5,5}:

        ____1____
       /         \
      2           2
     /  \        / \
    3    3      3   3
   /\    /\    /\
  4  4  4  4  4  4 
 /\
5  5

Let's start with the root node (1). As you can see, left subtree's depth is 5, while right subtree's depth is 4. Therefore, the condition for a height-balanced binary tree holds for the root node. We continue the same comparison recursively for both left and right subtree, and we conclude that this is indeed a balanced binary tree.

 

我AC的代码:我觉得我的代码就挺好挺短的。

bool isBalanced3(TreeNode* root){
        int depth = 0;
        return isBalancedDepth(root, depth);
    }

    bool isBalancedDepth(TreeNode* root, int &depth)
    {
        if(root == NULL) return true;
        int depthl = 0, depthr = 0;
        bool ans = isBalancedDepth(root->left, depthl) && isBalancedDepth(root->right, depthr) && abs(depthl - depthr) < 2;
        depth = ((depthl > depthr) ? depthl : depthr) + 1;
        return ans;
    }

 

其他人的代码,对高度多遍历了一遍,会比较慢:

bool isBalanced(TreeNode *root) {
        if (!root) return true;
        if (abs(depth(root->left) - depth(root->right)) > 1) return false;
        return isBalanced(root->left) && isBalanced(root->right);
    }
    int depth(TreeNode *node){
      if (!node) return 0;
      return max(depth(node->left) + 1, depth(node->right) + 1);
    }

 

转载于:https://www.cnblogs.com/dplearning/p/4481895.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值