【leetcode】111. Minimum Depth of Binary Tree

本文详细解析了寻找二叉树最小深度的算法,通过递归方式判断节点状态,包括叶子节点、单边子树及双边子树情况,最终实现高效求解最短路径到叶节点的节点数。

题目:
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.


思路:
对于每个node的判断,总共分三种情况:

  1. 无左子树,无右子树。此节点为叶子节点,返回1。
  2. 有左子树,无右子树。返回左子树高度+1。
  3. 无左子树,有右子树。返回右子树高度+1。
  4. 有左子树,有右子树。返回min(左子树高度,右子树高度)+1。

代码实现:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    
    int f(TreeNode* root){
        if (root == nullptr){
            return 0;
        }
        
        int left_depth = f(root->left);
        int right_depth = f(root->right);
        
        if (left_depth == 0 && right_depth == 0){
            return 1;
        }else if (left_depth == 0){
            return right_depth + 1;
        }else if (right_depth == 0){
            return left_depth + 1;
        }
        return min(left_depth, right_depth)+1;
        
    }
    int minDepth(TreeNode* root) {
        return f(root);
    }
};

discuss:

class Solution {
public:
    int minDepth(TreeNode* root) {
        if (!root) return 0;
        int left = minDepth(root->left);
        int right = minDepth(root->right);
        
        return (!left || !right) ? left + right + 1 : min(left, right) + 1;
    }
};
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值