forked from luliyucoordinate/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
1361.go
50 lines (47 loc) · 1.09 KB
/
1361.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
48
49
50
func validateBinaryTreeNodes(n int, leftChild []int, rightChild []int) bool {
d := make([]int, n)
for _, i := range leftChild {
if i != -1 {
d[i]++
}
}
for _, i := range rightChild {
if i != -1 {
d[i]++
}
}
root := -1
for i := 0; i < n; i++ {
if d[i] == 0 {
if root != -1 {
return false
}
root = i
}
}
if root == -1 {
return false
}
vis := make(map[int]int)
q := []int{root}
vis[root] = 1
for len(q) > 0 {
pre := q[0]
q = q[1:]
if leftChild[pre] != -1 {
if _, ok := vis[leftChild[pre]]; ok {
return false
}
vis[leftChild[pre]] = 1
q = append(q, leftChild[pre])
}
if rightChild[pre] != -1 {
if _, ok := vis[rightChild[pre]]; ok {
return false
}
vis[rightChild[pre]] = 1
q = append(q, rightChild[pre])
}
}
return len(vis) == n
}