-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.go
47 lines (46 loc) · 866 Bytes
/
Solution.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func longestConsecutive(root *TreeNode) int {
ans := 0
var dfs func(root *TreeNode) []int
dfs = func(root *TreeNode) []int {
if root == nil {
return []int{0, 0}
}
incr, decr := 1, 1
left := dfs(root.Left)
right := dfs(root.Right)
if root.Left != nil {
if root.Left.Val+1 == root.Val {
incr = left[0] + 1
}
if root.Left.Val-1 == root.Val {
decr = left[1] + 1
}
}
if root.Right != nil {
if root.Right.Val+1 == root.Val {
incr = max(incr, right[0]+1)
}
if root.Right.Val-1 == root.Val {
decr = max(decr, right[1]+1)
}
}
ans = max(ans, incr+decr-1)
return []int{incr, decr}
}
dfs(root)
return ans
}
func max(a, b int) int {
if a > b {
return a
}
return b
}