Skip to content

Commit e7d8936

Browse files
committed
add LeetCode 104. 二叉树的最大深度
1 parent 261d110 commit e7d8936

File tree

1 file changed

+120
-0
lines changed

1 file changed

+120
-0
lines changed

Diff for: 二叉树/LeetCode 104. 二叉树的最大深度.md

+120
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
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+
返回它的最大深度 3 。
25+
26+
来源:力扣(LeetCode)
27+
链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree
28+
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
29+
30+
31+
32+
## 解题思路
33+
34+
`dfs`,通过后续遍历求得,但是需要注意最后结果要加上根节点(即加1),并且需要判断一下树是不是为空,树为空的话直接返回 `0` 即可,不加 `1`
35+
36+
```javascript
37+
/**
38+
* Definition for a binary tree node.
39+
* function TreeNode(val) {
40+
* this.val = val;
41+
* this.left = this.right = null;
42+
* }
43+
*/
44+
/**
45+
* @param {TreeNode} root
46+
* @return {number}
47+
*/
48+
var maxDepth = function (root) {
49+
if(!root) return 0;
50+
let dfs = (root) => {
51+
if (root == null) return 0;
52+
// 后续遍历
53+
let left = root.left && dfs(root.left) + 1;
54+
let right = root.right && dfs(root.right) + 1;
55+
56+
return Math.max(left, right);
57+
}
58+
// 后续遍历结果还要加上根节点(即加1)
59+
return dfs(root) + 1;
60+
};
61+
```
62+
63+
64+
**解法二**
65+
66+
`bfs`,一层一层访问,每加一层计数器就加1,这样到达最后一层了直接返回我们的计数器结果即可。
67+
68+
```javascript
69+
/**
70+
* Definition for a binary tree node.
71+
* function TreeNode(val) {
72+
* this.val = val;
73+
* this.left = this.right = null;
74+
* }
75+
*/
76+
/**
77+
* @param {TreeNode} root
78+
* @return {number}
79+
*/
80+
var maxDepth = function(root) {
81+
if(!root) return 0
82+
let queue =[root]
83+
let cnt = 0
84+
while(queue.length){
85+
let size = queue.length
86+
while(size--){
87+
let node = queue.shift()
88+
if(node.left) queue.push(node.left)
89+
if(node.right) queue.push(node.right)
90+
}
91+
++cnt
92+
}
93+
return cnt
94+
};
95+
```
96+
97+
98+
99+
100+
## 最后
101+
文章产出不易,还望各位小伙伴们支持一波!
102+
103+
往期精选:
104+
105+
<a href="https://github.com/Chocolate1999/Front-end-learning-to-organize-notes">小狮子前端の笔记仓库</a>
106+
107+
<a href="https://github.com/Chocolate1999/leetcode-javascript">leetcode-javascript:LeetCode 力扣的 JavaScript 解题仓库,前端刷题路线(思维导图)</a>
108+
109+
小伙伴们可以在Issues中提交自己的解题代码,🤝 欢迎Contributing,可打卡刷题,Give a ⭐️ if this project helped you!
110+
111+
112+
<a href="https://yangchaoyi.vip/">访问超逸の博客</a>,方便小伙伴阅读玩耍~
113+
114+
![](https://img-blog.csdnimg.cn/2020090211491121.png#pic_center)
115+
116+
```javascript
117+
学如逆水行舟,不进则退
118+
```
119+
120+

0 commit comments

Comments
 (0)