[LeetCode] 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. 

二叉树的经典问题之最小深度问题就是就最短路径的节点个数,还是用深度优先搜索DFS来完成,万能的递归啊。。。请看代码:

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

求二叉树的最大深度可以参见我的博文:

http://www.cnblogs.com/grandyang/p/4051348.html

本文转自博客园Grandyang的博客,原文链接:[LeetCode] Minimum Depth of Binary Tree 二叉树的最小深度

,如需转载请自行联系原博主。

相关文章
|
7天前
【力扣刷题】二叉树的中序遍历、二叉树的最大深度、翻转二叉树、对称二叉树
【力扣刷题】二叉树的中序遍历、二叉树的最大深度、翻转二叉树、对称二叉树
14 0
|
10天前
|
存储 Java
JAVA数据结构刷题 -- 力扣二叉树
JAVA数据结构刷题 -- 力扣二叉树
16 0
|
11天前
[LeetCode]—— 226——翻转二叉树
[LeetCode]—— 226——翻转二叉树
|
11天前
[LeetCode]——965——单值二叉树
[LeetCode]——965——单值二叉树
|
11天前
LeetCode——101——对称二叉树
LeetCode——101——对称二叉树
35 12
|
11天前
|
存储
LeetCode———144—— 二叉树的前序遍历
LeetCode———144—— 二叉树的前序遍历
|
11天前
LeetCode——965. 单值二叉树
LeetCode——965. 单值二叉树
|
7天前
|
索引
【力扣刷题】两数求和、移动零、相交链表、反转链表
【力扣刷题】两数求和、移动零、相交链表、反转链表
15 2
【力扣刷题】两数求和、移动零、相交链表、反转链表
|
7天前
|
算法
"刷题记录:哈希表+双指针 | leetcode-2465. 不同的平均值数目 "
该文段是一篇关于编程题目的解答,主要讨论如何找到数组中所有不同平均值的个数。作者首先使用排序和哈希集来解决,将数组转为列表排序后,通过双指针计算平均值并存入哈希集以去重。然后,作者发现可以优化方案,通过双指针在排序后的数组中直接计算两数之和,用哈希集记录不重复的和,从而避免实际计算平均值,提高了算法效率。最终代码展示了这两种方法。
15 0
|
7天前
|
索引
【力扣刷题】删除链表的倒数第 N 个结点、两两交换链表中的节点、随机链表的复制
【力扣刷题】删除链表的倒数第 N 个结点、两两交换链表中的节点、随机链表的复制
13 0