File tree Expand file tree Collapse file tree 1 file changed +17
-12
lines changed Expand file tree Collapse file tree 1 file changed +17
-12
lines changed Original file line number Diff line number Diff line change @@ -19535,23 +19535,28 @@ public:
19535
19535
```
19536
19536
19537
19537
```go
19538
- // by chatGPT (go)
19538
+ // by mario_huang (go)
19539
+ var maxDiameter int
19540
+
19539
19541
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
19551
19544
maxDepth(root)
19552
19545
return maxDiameter
19553
19546
}
19554
19547
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
+
19555
19560
// 这是一种简单粗暴,但是效率不高的解法
19556
19561
func diameterOfBinaryTree(root *TreeNode) int {
19557
19562
if root == nil {
You can’t perform that action at this time.
0 commit comments