-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
Copy path1361-validate-binary-tree-nodes.java
47 lines (41 loc) · 1.26 KB
/
1361-validate-binary-tree-nodes.java
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
/* BFS
--------------------------------
Time Complexity: O(n)
Space Complexity: O(n)
------------------------------*/
class Solution {
public boolean validateBinaryTreeNodes(int n, int[] leftChild, int[] rightChild) {
int root = findRoot(n, leftChild, rightChild);
if(root == -1)
return false;
Set<Integer> visited = new HashSet<>();
Queue<Integer> q = new LinkedList<>();
q.add(root);
visited.add(root);
while(!q.isEmpty()){
int node = q.poll();
int[] childerns = {leftChild[node], rightChild[node]};
for(int c: childerns){
if(c == -1)
continue;
if(visited.contains(c))
return false;
q.add(c);
visited.add(c);
}
}
return visited.size() == n;
}
private int findRoot(int n, int[] leftChild, int[] rightChild){
Set<Integer> set = new HashSet<>();
for(int lc: leftChild)
set.add(lc);
for(int rc: rightChild)
set.add(rc);
for(int i = 0; i < n; i++){
if(!set.contains(i))
return i;
}
return -1;
}
}