Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[fix][golang] diameter-of-binary-tree #1602

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 23 additions & 23 deletions 多语言解法代码/solution_code.md
Original file line number Diff line number Diff line change
Expand Up @@ -19535,37 +19535,28 @@ 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)
}

// 这是一种简单粗暴,但是效率不高的解法
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 这个节点的直径
Expand All @@ -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
Expand Down