Skip to content

Commit 534c064

Browse files
committed
add LeetCode 543. 二叉树的直径
1 parent 366e43c commit 534c064

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
![](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9jZG4uanNkZWxpdnIubmV0L2doL2Nob2NvbGF0ZTE5OTkvY2RuL2ltZy8yMDIwMDgyODE0NTUyMS5qcGc?x-oss-process=image/format,png)
2+
>仰望星空的人,不应该被嘲笑
3+
4+
## 题目描述
5+
6+
给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过也可能不穿过根结点。
7+
8+
示例 :
9+
10+
```javascript
11+
给定二叉树
12+
13+
1
14+
/ \
15+
2 3
16+
/ \
17+
4 5
18+
返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。
19+
```
20+
21+
**注意**:两结点之间的路径长度是以它们之间边的数目表示。
22+
23+
来源:力扣(LeetCode)
24+
链接:https://leetcode-cn.com/problems/diameter-of-binary-tree
25+
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
26+
27+
## 解题思路
28+
29+
通过**后序遍历**,每一次返回当前根节点下的左右孩子的深度最大值,然后每一次递归求一下左右孩子路径和的最大值即可。
30+
31+
```javascript
32+
/**
33+
* Definition for a binary tree node.
34+
* function TreeNode(val) {
35+
* this.val = val;
36+
* this.left = this.right = null;
37+
* }
38+
*/
39+
/**
40+
* @param {TreeNode} root
41+
* @return {number}
42+
*/
43+
var diameterOfBinaryTree = function (root) {
44+
if (!root) return 0;
45+
let res = 0;
46+
let dfs = (root) => {
47+
if (!root) return 0;
48+
// 后序遍历 先遍历左孩子
49+
let left = root.left && dfs(root.left) + 1;
50+
let right = root.right && dfs(root.right) + 1;
51+
// 每次求直径,比较左右孩子路径和的最大值
52+
res = Math.max(left + right, res);
53+
// 递归时候返回左右孩子深度最长
54+
return Math.max(left, right)
55+
}
56+
dfs(root);
57+
return res;
58+
};
59+
```
60+
61+
62+
63+
64+
65+
## 最后
66+
文章产出不易,还望各位小伙伴们支持一波!
67+
68+
往期精选:
69+
70+
<a href="https://github.com/Chocolate1999/Front-end-learning-to-organize-notes">小狮子前端の笔记仓库</a>
71+
72+
<a href="https://github.com/Chocolate1999/leetcode-javascript">leetcode-javascript:LeetCode 力扣的 JavaScript 解题仓库,前端刷题路线(思维导图)</a>
73+
74+
小伙伴们可以在Issues中提交自己的解题代码,🤝 欢迎Contributing,可打卡刷题,Give a ⭐️ if this project helped you!
75+
76+
77+
<a href="https://yangchaoyi.vip/">访问超逸の博客</a>,方便小伙伴阅读玩耍~
78+
79+
![](https://img-blog.csdnimg.cn/2020090211491121.png#pic_center)
80+
81+
```javascript
82+
学如逆水行舟,不进则退
83+
```
84+
85+

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy