Skip to content

Commit

Permalink
add sol
Browse files Browse the repository at this point in the history
  • Loading branch information
ductnn committed Feb 27, 2024
1 parent 01e1aef commit dcada1d
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions leetcode/543.DiameterofBinaryTree/diameterofBinaryTree.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// https://leetcode.com/problems/diameter-of-binary-tree

package main

/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/

type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}

func diameterOfBinaryTree(root *TreeNode) int {
ans := 0
var dfs func(root *TreeNode) int
dfs = func(root *TreeNode) int {
if root == nil {
return 0
}
left, right := dfs(root.Left), dfs(root.Right)
ans = max(ans, left+right)
return 1 + max(left, right)
}
dfs(root)
return ans
}

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

0 comments on commit dcada1d

Please sign in to comment.