Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 9968397

Browse files
diameter-of-binary-tree (labuladong#1569)
1 parent 435c10b commit 9968397

File tree

1 file changed

+17
-12
lines changed

1 file changed

+17
-12
lines changed

‎多语言解法代码/solution_code.md

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -19535,23 +19535,28 @@ public:
1953519535
```
1953619536

1953719537
```go
19538-
// by chatGPT (go)
19538+
// by mario_huang (go)
19539+
var maxDiameter int
19540+
1953919541
func diameterOfBinaryTree(root *TreeNode) int {
19540-
maxDiameter := 0
19541-
maxDepth := func(root *TreeNode) int {
19542-
if root == nil {
19543-
return 0
19544-
}
19545-
leftMax := maxDepth(root.Left)
19546-
rightMax := maxDepth(root.Right)
19547-
// 后序遍历位置顺便计算最大直径
19548-
maxDiameter = max(maxDiameter, leftMax+rightMax)
19549-
return 1 + max(leftMax, rightMax)
19550-
}
19542+
// 记录最大直径的长度
19543+
maxDiameter = 0
1955119544
maxDepth(root)
1955219545
return maxDiameter
1955319546
}
1955419547

19548+
func maxDepth(root *TreeNode) int {
19549+
if root == nil {
19550+
return 0
19551+
}
19552+
leftMax := maxDepth(root.Left)
19553+
rightMax := maxDepth(root.Right)
19554+
// 后序位置,顺便计算最大直径
19555+
myDiameter := leftMax + rightMax
19556+
maxDiameter = max(maxDiameter, myDiameter)
19557+
return max(leftMax, rightMax) + 1
19558+
}
19559+
1955519560
// 这是一种简单粗暴,但是效率不高的解法
1955619561
func diameterOfBinaryTree(root *TreeNode) int {
1955719562
if root == nil {

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /