Skip to content

Commit 3aa2ac6

Browse files
committed
✨543.二叉树的直径
1 parent 2ecb1f7 commit 3aa2ac6

File tree

3 files changed

+58
-0
lines changed

3 files changed

+58
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@
6060
- [387.字符串中的第一个唯一字符](leetcode/easy/387.go)
6161
- [415.字符串相加](leetcode/easy/t415/solution.go)
6262
- [521.最长特殊序列 Ⅰ](leetcode/easy/521.go)
63+
- [543.二叉树的直径](leetcode/easy/t543/solution.go)
6364
- [566.重塑矩阵](leetcode/easy/556.go)
6465
- [590.N 叉树的后序遍历](leetcode/easy/590.go)
6566
- [653.两数之和 IV-输入 BST](leetcode/easy/653.go)

leetcode/easy/t543/solution.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package t543
2+
3+
import (
4+
. "github.com/techoc/leetcodego/leetcode/utils"
5+
)
6+
7+
// 543. 二叉树的直径
8+
// https://leetcode.cn/problems/diameter-of-binary-tree/
9+
func diameterOfBinaryTree(root *TreeNode) int {
10+
var res = 0 // 初始化结果变量为0
11+
var depth func(*TreeNode) int // 声明一个内部函数,用于计算节点的深度
12+
13+
// 定义depth函数,用于递归计算二叉树的深度并更新结果
14+
depth = func(node *TreeNode) int {
15+
if node == nil {
16+
return 0 // 如果节点为空,深度为0
17+
}
18+
l := depth(node.Left) // 计算左子树的深度
19+
r := depth(node.Right) // 计算右子树的深度
20+
res = max(res, l+r) // 更新结果为左右子树深度之和的最大值
21+
return max(l, r) + 1 // 返回节点的深度,即左右子树最大深度加一
22+
}
23+
depth(root) // 从根节点开始计算深度
24+
return res // 返回结果
25+
}

leetcode/easy/t543/solution_test.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package t543
2+
3+
import (
4+
"github.com/techoc/leetcodego/leetcode/utils"
5+
"testing"
6+
)
7+
8+
func TestDiameterOfBinaryTree(t *testing.T) {
9+
tests := []struct {
10+
name string
11+
root *utils.TreeNode
12+
want int
13+
}{
14+
{
15+
name: "Case 1",
16+
root: utils.ListToTree([]any{1, 2, 3, 4, 5}),
17+
want: 3,
18+
},
19+
{
20+
name: "Case 2",
21+
root: utils.ListToTree([]any{1, 2}),
22+
want: 1,
23+
},
24+
}
25+
for _, tt := range tests {
26+
t.Run(tt.name, func(t *testing.T) {
27+
if got := diameterOfBinaryTree(tt.root); got != tt.want {
28+
t.Errorf("diameterOfBinaryTree() = %v, want %v", got, tt.want)
29+
}
30+
})
31+
}
32+
}

0 commit comments

Comments
 (0)