29 lines
515 B
Go
29 lines
515 B
Go
|
|
package main
|
||
|
|
|
||
|
|
type TreeNode struct {
|
||
|
|
Val int
|
||
|
|
Left *TreeNode
|
||
|
|
Right *TreeNode
|
||
|
|
}
|
||
|
|
|
||
|
|
func main() {
|
||
|
|
|
||
|
|
}
|
||
|
|
|
||
|
|
func diameterOfBinaryTree(root *TreeNode) int {
|
||
|
|
a, b := maxpath(root.Right)
|
||
|
|
c, d := maxpath(root.Left)
|
||
|
|
return max(a+b, c, d)
|
||
|
|
}
|
||
|
|
|
||
|
|
func maxpath(p *TreeNode) (int, int) {
|
||
|
|
if p == nil {
|
||
|
|
return 0, 0
|
||
|
|
}
|
||
|
|
leftpathnum, leftcurmax := maxpath(p.Left)
|
||
|
|
rightpathnum, rightcurmax := maxpath(p.Right)
|
||
|
|
curmax := max(leftpathnum+rightpathnum, leftcurmax, rightcurmax)
|
||
|
|
|
||
|
|
return 1 + max(leftpathnum+rightpathnum), curmax
|
||
|
|
}
|