Thanks to visit codestin.com Credit goes to github.com
We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
2 parents 693d6a3 + edbd936 commit dab0fefCopy full SHA for dab0fef
go/543-Diameter-of-Binary-Tree.go
@@ -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