Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit dab0fef

Browse files
authored
Merge pull request #1235 from thecodeboy/diameterOfBinaryTree
Create: 543-Diameter-of-Binary-Tree.go
2 parents 693d6a3 + edbd936 commit dab0fef

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

go/543-Diameter-of-Binary-Tree.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* type TreeNode struct {
4+
* Val int
5+
* Left *TreeNode
6+
* Right *TreeNode
7+
* }
8+
*/
9+
func diameterOfBinaryTree(root *TreeNode) int {
10+
maxLength := 0
11+
dfs(root, &maxLength)
12+
return maxLength
13+
}
14+
15+
func dfs(t *TreeNode, maxLength *int) int {
16+
if t == nil {
17+
return 0
18+
}
19+
20+
left := dfs(t.Left, maxLength)
21+
right := dfs(t.Right, maxLength)
22+
*maxLength = max(*maxLength, left+right)
23+
24+
return max(left, right) + 1
25+
}
26+
27+
func max(a, b int) int {
28+
if a > b {
29+
return a
30+
}
31+
return b
32+
}

0 commit comments

Comments
 (0)