leetcode111. 二叉树的最小深度
二叉树 深度 最小
2023-09-27 14:25:55 时间
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最小深度 2.
思路:见代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int minDepth(TreeNode root) {
if(root == null) return 0;
//左孩子和有孩子都为空的情况,说明到达了叶子节点,返回1
if(root.left == null && root.right == null) return 1;
//左孩子和由孩子其中一个为空,返回较大深度
int m1 = minDepth(root.left);
int m2 = minDepth(root.right);
//其中一个节点为空,说明有一个必为0,所以可以返回m1 + m2 + 1;
if(root.left == null || root.right == null) return m1 + m2 + 1;
//左右孩子都不为空,返回最小深度+1
return Math.min(m1,m2) + 1;
}
}
相关文章
- 【算法】【二叉树模块】判断一棵二叉树是否为搜索二叉树和完全二叉树
- 二叉树、多叉树子路径遍历
- 二叉树的最大深度
- 【Leetcode】111. 二叉树的最小深度
- 【C++】AVL树,平衡二叉树详细解析
- 二叉树的遍历
- [LeetCode]104. 二叉树的最大深度
- [leetcode]面试题55 - I. 二叉树的深度
- PTA - 6-1 输出二叉树的所有叶子 (15 分)
- LeetCode199之二叉树的右视图(二叉树的深度遍历和广度遍历)
- 91、【树与二叉树】leetcode ——559.n叉树的最大深度(递归DFS+迭代BFS)(C++版本)
- 【二叉树】之力扣牛客必刷题
- 面试题23_从上往下打印二叉树
- SDUTOJ 2804求二叉树的深度
- 数据结构_二叉树
- [LintCode] Maximum Depth of Binary Tree 二叉树的最大深度
- [LeetCode] 111. Minimum Depth of Binary Tree 二叉树的最小深度
- 26数据结构与算法分析之---线索二叉树