From 17aa3deff4aea29172a1372bf2441d24a195ce55 Mon Sep 17 00:00:00 2001 From: qintianxing Date: Mon, 3 Jun 2024 11:09:51 +0800 Subject: [PATCH] fix diameter-of-binary-tree golang --- .../solution_code.md" | 46 +++++++++---------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git "a/\345\244\232\350\257\255\350\250\200\350\247\243\346\263\225\344\273\243\347\240\201/solution_code.md" "b/\345\244\232\350\257\255\350\250\200\350\247\243\346\263\225\344\273\243\347\240\201/solution_code.md" index 64a8b95919..fe8f712cb7 100644 --- "a/\345\244\232\350\257\255\350\250\200\350\247\243\346\263\225\344\273\243\347\240\201/solution_code.md" +++ "b/\345\244\232\350\257\255\350\250\200\350\247\243\346\263\225\344\273\243\347\240\201/solution_code.md" @@ -19535,21 +19535,21 @@ public: ``` ```go -// by chatGPT (go) func diameterOfBinaryTree(root *TreeNode) int { - maxDiameter := 0 - maxDepth := func(root *TreeNode) int { - if root == nil { - return 0 - } - leftMax := maxDepth(root.Left) - rightMax := maxDepth(root.Right) - // 后序遍历位置顺便计算最大直径 - maxDiameter = max(maxDiameter, leftMax+rightMax) - return 1 + max(leftMax, rightMax) - } - maxDepth(root) - return maxDiameter + maxDiameter := 0 + maxDepth(root, &maxDiameter) + return maxDiameter +} + +func maxDepth(node *TreeNode, maxDiameter *int) int { + if node == nil { + return 0 + } + leftMax := maxDepth(node.Left, maxDiameter) + rightMax := maxDepth(node.Right, maxDiameter) + // Calculate the diameter + *maxDiameter = max(*maxDiameter, leftMax+rightMax) + return 1 + max(leftMax, rightMax) } // 这是一种简单粗暴,但是效率不高的解法 @@ -19557,15 +19557,6 @@ func diameterOfBinaryTree(root *TreeNode) int { if root == nil { return 0 } - // 计算出左右子树的最大高度 - maxDepth := func(root *TreeNode) int { - if root == nil { - return 0 - } - leftMax := maxDepth(root.Left) - rightMax := maxDepth(root.Right) - return 1 + max(leftMax, rightMax) - } leftMax := maxDepth(root.Left) rightMax := maxDepth(root.Right) // root 这个节点的直径 @@ -19576,6 +19567,15 @@ func diameterOfBinaryTree(root *TreeNode) int { diameterOfBinaryTree(root.Right))) } +func maxDepth(node *TreeNode) int { + if node == nil { + return 0 + } + leftMax := maxDepth(node.Left) + rightMax := maxDepth(node.Right) + return 1 + max(leftMax, rightMax) +} + func max(a, b int) int { if a > b { return a