树 求树的最小深度、最大深度

本文介绍了二叉树的最小深度和最大深度问题的两种解决方法。通过递归方式,分别计算左右子树的深度,并根据不同的情况进行判断和返回。适用于算法初学者和技术面试准备。

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

一、二叉树的最小深度

Given a binary tree, find its minimum depth.The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

求解此类问题要先明确递归状态及递归条件,考虑清楚是否有漏洞。本题有两种解法。

解法一:分别存储左右子树的深度,返回他们中的较小值。注意:要考虑到只有一个子节点的情况。

Class Solution {

public:
    int run(TreeNode *root) {
        if(!root) return 0;
        int l = 0, r = 0;
        if(root->left)  l = run(root->left);
        if(root->right)  r = run(root->right);
        if(root->left && root->right) return min(l, r)+1;
        else return l+r+1;

    }
};

解法二:

Class Solution {

public:
    int run(TreeNode *root) {
        if(!root) return 0;
        if(!root->left)  return run(root->right)+1;
        if(!root->right)  return run(root->left)+1;
        return min(run(root->right), run(root->left))+1;       
    }
};

二、二叉树的最大深度

链接:https://www.nowcoder.com/questionTerminal/8a2b2bf6c19b4f23a9bdb9b233eefa73
来源:牛客网

Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

同上述最小深度方法类似,也可用两种方法求解:

class Solution {
public:
    int maxDepth(TreeNode *root) {
        if(!root) return 0;
        int l = 0, r = 0;
        if(root->right) r = maxDepth(root->right);
        if(root->left) l = maxDepth(root->left);
        return max(l, r)+1;
    }
};
class Solution {
public:
    int maxDepth(TreeNode *root) {
        if(!root) return 0;
        if(root->right && root->left) 
            return max(maxDepth(root->left), maxDepth(root->right))+1;
        if(root->right) return maxDepth(root->right)+1;
        if(root->left) return maxDepth(root->left)+1;
        return 1;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值