Skip to content

Commit 261d110

Browse files
committed
add LeetCode 111. 二叉树的最小深度
1 parent 2ba59bb commit 261d110

File tree

1 file changed

+90
-0
lines changed

1 file changed

+90
-0
lines changed

Diff for: 二叉树/LeetCode 111. 二叉树的最小深度.md

+90
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
![](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9jZG4uanNkZWxpdnIubmV0L2doL2Nob2NvbGF0ZTE5OTkvY2RuL2ltZy8yMDIwMDgyODE0NTUyMS5qcGc?x-oss-process=image/format,png)
2+
>仰望星空的人,不应该被嘲笑
3+
4+
## 题目描述
5+
6+
给定一个二叉树,找出其最小深度。
7+
8+
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
9+
10+
说明: 叶子节点是指没有子节点的节点。
11+
12+
示例:
13+
14+
```javascript
15+
给定二叉树 [3,9,20,null,null,15,7],
16+
17+
3
18+
/ \
19+
9 20
20+
/ \
21+
15 7
22+
23+
```
24+
返回它的最小深度 2.
25+
26+
来源:力扣(LeetCode)
27+
链接:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree
28+
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
29+
30+
31+
32+
## 解题思路
33+
34+
`dfs`,对于当前节点,判断一下是否有左右孩子,有的话就取左右孩子得到的最小深度,如果只有左孩子,递归左孩子,只有有孩子,则递归右孩子。到子节点时,直接返回 `1`
35+
36+
![](https://img-blog.csdnimg.cn/20200925143150363.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MjQyOTcxOA==,size_16,color_FFFFFF,t_70#pic_center)
37+
38+
39+
```javascript
40+
/**
41+
* Definition for a binary tree node.
42+
* function TreeNode(val) {
43+
* this.val = val;
44+
* this.left = this.right = null;
45+
* }
46+
*/
47+
/**
48+
* @param {TreeNode} root
49+
* @return {number}
50+
*/
51+
var minDepth = function(root) {
52+
let dfs = (root) => {
53+
if(root == null) return 0;
54+
// 左右孩子都有,取左右孩子的最小值
55+
if(root.left && root.right){
56+
return 1 + Math.min(dfs(root.left),dfs(root.right));
57+
}else if(root.left){
58+
return 1 + dfs(root.left);
59+
}else if(root.right){
60+
return 1 + dfs(root.right);
61+
}
62+
return 1;
63+
}
64+
return dfs(root);
65+
};
66+
```
67+
68+
69+
70+
## 最后
71+
文章产出不易,还望各位小伙伴们支持一波!
72+
73+
往期精选:
74+
75+
<a href="https://github.com/Chocolate1999/Front-end-learning-to-organize-notes">小狮子前端の笔记仓库</a>
76+
77+
<a href="https://github.com/Chocolate1999/leetcode-javascript">leetcode-javascript:LeetCode 力扣的 JavaScript 解题仓库,前端刷题路线(思维导图)</a>
78+
79+
小伙伴们可以在Issues中提交自己的解题代码,🤝 欢迎Contributing,可打卡刷题,Give a ⭐️ if this project helped you!
80+
81+
82+
<a href="https://yangchaoyi.vip/">访问超逸の博客</a>,方便小伙伴阅读玩耍~
83+
84+
![](https://img-blog.csdnimg.cn/2020090211491121.png#pic_center)
85+
86+
```javascript
87+
学如逆水行舟,不进则退
88+
```
89+
90+

0 commit comments

Comments
 (0)