Skip to content

Commit 987a172

Browse files
committed
add: 543.二叉树的直径
1 parent 8b25c04 commit 987a172

File tree

2 files changed

+80
-0
lines changed

2 files changed

+80
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,7 @@
120120
- [x] [404.左叶子之和](./basic/binary-tree/ext-sum-of-left-leaves.md)
121121
- [x] [257.二叉树的所有路径](./basic/binary-tree/ext-binary-tree-paths.md)
122122
- [x] [112.路径总和](./basic/binary-tree/ext-path-sum.md)
123+
- [x] [543.二叉树的直径](./basic/binary-tree/ext-diameter-of-binary-tree.md)
123124

124125
### 哈希表
125126

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
# 543. 二叉树的直径
2+
3+
https://leetcode-cn.com/problems/diameter-of-binary-tree/
4+
5+
## 题目描述
6+
7+
```
8+
给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过也可能不穿过根结点。
9+
10+
 
11+
12+
示例 :
13+
给定二叉树
14+
15+
1
16+
/ \
17+
2 3
18+
/ \
19+
4 5
20+
返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。
21+
22+
 
23+
24+
注意:两结点之间的路径长度是以它们之间边的数目表示。
25+
26+
来源:力扣(LeetCode)
27+
链接:https://leetcode-cn.com/problems/diameter-of-binary-tree
28+
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
29+
```
30+
31+
## 方法1: DFS
32+
33+
### 思路
34+
35+
题目的意思就是要找到一个子树,满足条件“其左子树高度+右子树高度值最大”,返回这个最大值。
36+
37+
要找到符合条件的子树,只需要在计算二叉树高度的同时用一个全局变量来记录就行。
38+
39+
### 复杂度分析
40+
41+
- 时间复杂度:$O(N)$,N 是二叉树节点数。
42+
- 空间复杂度:$O(h)$,h 是二叉树的高度。
43+
44+
### 代码
45+
46+
JavaScript Code
47+
48+
```js
49+
/**
50+
* Definition for a binary tree node.
51+
* function TreeNode(val) {
52+
* this.val = val;
53+
* this.left = this.right = null;
54+
* }
55+
*/
56+
/**
57+
* @param {TreeNode} root
58+
* @return {number}
59+
*/
60+
var diameterOfBinaryTree = function(root) {
61+
let max = 0
62+
dfs(root)
63+
return max
64+
65+
// ****************************************
66+
function dfs(root) {
67+
if (!root) return 0
68+
if (!root.left && !root.right) return 1
69+
70+
const leftH = dfs(root.left)
71+
const rightH = dfs(root.right)
72+
if (leftH + rightH > max) max = leftH + rightH
73+
74+
return Math.max(leftH, rightH) + 1
75+
}
76+
};
77+
```
78+
79+
更多题解可以访问:[https://github.com/suukii/91-days-algorithm](https://github.com/suukii/91-days-algorithm)

0 commit comments

Comments
 (0)