LeetCode_110. 平衡二叉树_111. 二叉树的最小深度_递归

110.平衡二叉树

给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。

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

提示:
树中的节点数在范围 [0, 5000] 内
-104 <= Node.val <= 104

来源:https://leetcode-cn.com/problems/balanced-binary-tree/

优秀解答:[育树霖疯]平衡二叉树(Java视频讲解,清晰易懂带字幕)

C代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
int deep(struct TreeNode* node){
    //退出条件
    if(node==NULL) return 0;
    //单层逻辑:计算深度
    //深度=Max(左节点深度,右节点深度)+1
    return fmax(deep(node->left),deep(node->right))+1;
}

bool isBalanced(struct TreeNode* root){
    //根结点为NULL一定是
    if(root==NULL) return true;

    //还要排除对称二叉树的情况 这种情况看子问题时是false,但是总体看,是true
    /*
            1
        2        3
    2                 5
4                          6
    */
    //if(!root->left||!root->right) return false;
    if(!isBalanced(root->left)||!isBalanced(root->right)) return false;

    int leftDeep = deep(root->left);
    int rightDeep = deep(root->right);
    return fabs(leftDeep-rightDeep)>1?false:true;
}

111. 二叉树的最小深度

给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。

在这里插入图片描述

提示:
树中节点数的范围在 [0, 105] 内
-1000 <= Node.val <= 1000

来源:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/

没有考虑到只有一颗子树的情况,如图
在这里插入图片描述

return fmin(leftDeep,rightDeep)+1;是错误的,考虑的情况欠缺。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */


int minDepth(struct TreeNode* root){
    if(root==NULL) return 0;
    if(root->left==NULL&&root->right==NULL) return 1;
    int leftDeep = minDepth(root->left);
    int rightDeep= minDepth(root->right);

    // 如果左子树或右子树的深度有一个为 0,即只存在一个子树,那么当前子树的最小深度就是该子树的深度+1
    // 如果左子树和右子树的深度都不为 0,即左右子树都存在,那么当前子树的最小深度就是它们较小值+1
    return (leftDeep== 0 || rightDeep == 0) ? leftDeep + rightDeep + 1 : fmin(leftDeep, rightDeep) + 1;
    //return fmin(leftDeep,rightDeep)+1;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值