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.

示例1:

输入: (1,2,3,4,5)  输出:2

代码:

复制代码
 1 /**
 2  * struct TreeNode {
 3  *    int val;
 4  *    struct TreeNode *left;
 5  *    struct TreeNode *right;
 6  * };
 7  */
 8 
 9 class Solution {
10 public:
11     /**
12      * 
13      * @param root TreeNode类 
14      * @return int整型
15      */
16     int run(TreeNode* root) {
17         if( root == NULL)
18             return 0;
19         if( root->left == NULL && root->right == NULL)
20             return 1;
21         // 当左/右子树为空时,要找到该子树深度
22         if( root->left == NULL || root->right == NULL)
23             return max(run(root->left), run(root->right))+1;
24         return min(run(root->left), run(root->right))+1;
25     }
26 };
复制代码

我的笔记:

  利用递归的方法找到最小深度,但会有左/右子树为空的情况,会干扰比较,所以需要单独将这种情况做处理,即:找到该子树的深度。

posted @   John_yan15  阅读(174)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示