Skip to content

Commit

Permalink
Merge pull request neetcode-gh#1235 from thecodeboy/diameterOfBinaryTree
Browse files Browse the repository at this point in the history
Create: 543-Diameter-of-Binary-Tree.go
  • Loading branch information
Ahmad-A0 authored Oct 8, 2022
2 parents 693d6a3 + edbd936 commit dab0fef
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions go/543-Diameter-of-Binary-Tree.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func diameterOfBinaryTree(root *TreeNode) int {
maxLength := 0
dfs(root, &maxLength)
return maxLength
}

func dfs(t *TreeNode, maxLength *int) int {
if t == nil {
return 0
}

left := dfs(t.Left, maxLength)
right := dfs(t.Right, maxLength)
*maxLength = max(*maxLength, left+right)

return max(left, right) + 1
}

func max(a, b int) int {
if a > b {
return a
}
return b
}

0 comments on commit dab0fef

Please sign in to comment.